Spring_对JDBC的支持

使用JdbcTemplate更新数据库

导入jar包

创建applicationcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 导入资源文件 -->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <!-- 配置C3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean> <!-- 配置Spring的jdbcTemplate -->
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>

创建db.properties文件

jdbc.user=root
jdbc.password=password
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring4?serverTimezone=GMT%2B8 jdbc.initPoolSize=5
jdbc.maxPoolSize=10

创建测试类

package com.tanlei.pojo.jdbc;

import static org.junit.jupiter.api.Assertions.*;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import javax.sql.DataSource; import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import junit.framework.TestListener; public class JDBCTest {
 private ApplicationContext ctx=null;
private JdbcTemplate jdbcTemplate;
{
ctx=new ClassPathXmlApplicationContext("applicationcontext.xml");
jdbcTemplate=(JdbcTemplate) ctx.getBean("jdbcTemplate"); }

/**
*
*tanlei
*2018年12月26日
*执行INSERT UPDATE DELETE
*/
//单独修改一条语句
//update
@Test
public void testUpdate() {
String sql="update employee set EMP_NAME=? where EMP_ID=?";
jdbcTemplate.update(sql,"tanlei",769);
} //批量增加数据,修改,删除
//batchUpdate
@Test
public void testAlladd() {
String sql="insert into DEPARTMENT(DEPT_ID,DEPT_NAME,DEPT_NO) values (?,?,?)";
List<Object[]> batchArgs=new ArrayList<>();
batchArgs.add(new Object[] {1,"AA","D1"});
batchArgs.add(new Object[] {2,"BB","D2"});
jdbcTemplate.batchUpdate(sql, batchArgs);
} //从数据库获取一条记录,实际上得到一个对象
//queryForObject 使用sql中的列的 别名完成列名和属性名的映射
//jdbcTemplate是一个jdbc的小工具,不是orm框架
@Test
public void testemployee() {
String sql="select EMP_ID as id,EMP_NAME as empname,EMP_NO as empno,JOB as job from employee where EMP_ID=?";
RowMapper<Employee> rowMapper=new BeanPropertyRowMapper<>(Employee.class);
Employee employee=jdbcTemplate.queryForObject(sql, rowMapper,769);
System.out.println(employee);
} //查到实体类的集合
@Test
public void TestList() {
String sql="select EMP_ID as id,EMP_NAME as empname,EMP_NO as empno,JOB as job from employee where EMP_ID>?";
RowMapper<Employee> rowMapper=new BeanPropertyRowMapper<>(Employee.class);
List<Employee> employees=jdbcTemplate.query(sql, rowMapper,769);
System.out.println(employees);
} //获取某一个属性值,或做统计查询
@Test
public void testListForObject() {
String sql="select count(EMP_ID) as id from employee ";
long count=jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count);
}
@Test
public void testDataSource() throws SQLException {
DataSource dataSource=ctx.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
}


}

1.查询单行数据

1.1 自定义RowMapper

public class RowMapper implements org.springframework.jdbc.core.RowMapper {
@Override
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Customer customer=new Customer();
customer.setCustid(resultSet.getInt("cus_id"));
customer.setName(resultSet.getString("name"));
customer.setAge(resultSet.getInt("age"));
return null;
}
}

它传递给 queryForObject()方法,返回的结果将调用自定义 mapRow()方法的值匹配到属性

public Customer findByCustomerId(int custId){

    String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?";

    Customer customer = (Customer)getJdbcTemplate().queryForObject(
sql, new Object[] { custId }, new CustomerRowMapper()); return customer;
}

1.2 BeanPropertyRowMapper

在Spring2.5中,带有一个方便 RowMapper 实现所谓“BeanPropertyRowMapper”,它可以通过匹配行的名字的列值映射到一个属性。只要确保这两个属性和列具有相同的名称,如属性“CUSTID'将匹配到列名为:”CUSTID'或下划线“CUST_ID”。

public Customer findByCustomerId2(int custId){

    String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?";

    Customer customer = (Customer)getJdbcTemplate().queryForObject(
sql, new Object[] { custId },
new BeanPropertyRowMapper(Customer.class)); return customer;
}

2,查询多行

现在,查询或从数据库中提取多行,并且将它转换成一个列表。

2.1手动映射它

返回多行,RowMapper 不支持 queryForList()方法,需要手动映射它。 
public List<Customer> findAll(){

    String sql = "SELECT * FROM CUSTOMER";

    List<Customer> customers = new ArrayList<Customer>();

    List<Map> rows = getJdbcTemplate().queryForList(sql);
for (Map row : rows) {
Customer customer = new Customer();
customer.setCustId((Long)(row.get("CUST_ID")));
customer.setName((String)row.get("NAME"));
customer.setAge((Integer)row.get("AGE"));
customers.add(customer);
} return customers;
}

2.2 BeanPropertyRowMapper

最简单的解决方案是使用 BeanPropertyRowMapper 类。 
public List<Customer> findAll(){

    String sql = "SELECT * FROM CUSTOMER";

    List<Customer> customers  = getJdbcTemplate().query(sql,
new BeanPropertyRowMapper(Customer.class)); return customers;
}

继承JdbcDaoSupport(不推荐使用,而推进直接使用

jdbcTemplate

)

Spring_使用(JDBC)的更多相关文章

  1. Spring_总结_04_高级配置(一)_Profile

    一.前言 本文承接上一节:Spring_总结_03_装配Bean(四)之导入与混合配置 这一节,来总结一下profile. 我们在开发软件时,通常会进行跨环境部署.而在跨环境部署时,经常会遇到某些环境 ...

  2. Java数据库连接技术——JDBC

    大家好,今天我们学习了Java如何连接数据库.之前学过.net语言的数据库操作,感觉就是一通百通,大同小异. JDBC是Java数据库连接技术的简称,提供连接各种常用数据库的能力. JDBC API ...

  3. 玩转spring boot——结合AngularJs和JDBC

    参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...

  4. [原创]java使用JDBC向MySQL数据库批次插入10W条数据测试效率

    使用JDBC连接MySQL数据库进行数据插入的时候,特别是大批量数据连续插入(100000),如何提高效率呢?在JDBC编程接口中Statement 有两个方法特别值得注意:通过使用addBatch( ...

  5. JDBC MySQL 多表关联查询查询

    public static void main(String[] args) throws Exception{ Class.forName("com.mysql.jdbc.Driver&q ...

  6. JDBC增加删除修改

    一.配置程序--让我们程序能找到数据库的驱动jar包 1.把.jar文件复制到项目中去,整合的时候方便. 2.在eclipse项目右击"构建路径"--"配置构建路径&qu ...

  7. JDBC简介

    jdbc连接数据库的四个对象 DriverManager  驱动类   DriverManager.registerDriver(new com.mysql.jdbc.Driver());不建议使用 ...

  8. JDBC Tutorials: Commit or Rollback transaction in finally block

    http://skeletoncoder.blogspot.com/2006/10/jdbc-tutorials-commit-or-rollback.html JDBC Tutorials: Com ...

  9. FineReport如何用JDBC连接阿里云ADS数据库

    在使用FineReport连接阿里云的ADS(AnalyticDB)数据库,很多时候在测试连接时就失败了.此时,该如何连接ADS数据库呢? 我们只需要手动将连接ads数据库需要使用到的jar放置到%F ...

随机推荐

  1. php 网页内容抓取

    最近抓的2个网站内容的代码 列表页抓取:第一种使用phpquery插件,可以快速获取,第二种它是api,所以直接获取 load_third("phpQuery.php"); /** ...

  2. MaxCompute问答整理之8月

    本文是基于对MaxCompute产品的学习进度,再结合开发者社区里面的一些问题,进而整理成文.希望对大家有所帮助. 问题一.通过数据源数据增量同步后,如何查看某一条数据具体被同步到MaxCompute ...

  3. ArccGIS 10发布WFS服务并加载到Skyline中

    下面用ArcGIS Server 10.0将建筑物图层发布为WFS服务. (1)创建mxd文件.ArcMap打开建筑物图层,存为Buildings.mxd文件.注意:必须统一空间参考系,且要与图层的坐 ...

  4. linux命令行操作mysql数据库明细

    连接数据库==> mysql -uroot -p 输入root密码 进入mysql操作后 下面的命令不要忘了最后结尾的; 1.选择数据库命令: use <数据库名> 2.查看表的引擎 ...

  5. eureka注册中心设置用户名密码

    1.加入安全认证依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId ...

  6. 代理模式(Proxy、Subject、RealSubject)(代购火车票)

    .(为其他对象提供一种代理以控制对这个对象的访问.) 在实际的软件开发中,我们经常面临着对一个对象进行访问控制的问题,由于跨越网络或安全方面等原因不能直接或不需要直接被访问,直接访问的代价会给系统带来 ...

  7. storm-jdbc的使用

    最近项目组分配到研究storm-jdbc用法 发现网上关于insert和query方法挺多的,但是自定义方法很少.而且用法上也挺多缺陷.在此自己总结记录一下 JdbcInsertBolt 的核心代码 ...

  8. python打包成为exe文件

    pyinstaller 库的使用 PyInstaller是一个十分有用的第三方库,它能够在Windows.Linux.Mac OS X 等操作系统下将 Python 源文件打包,通过对源文件打包,Py ...

  9. JavaScript中this的指向(转载)

    转载自:http://www.cnblogs.com/dongcanliang/p/7054176.html 前言 this 指向问题是入坑前端必须了解知识点,现在迎来了ES6时代,因为箭头函数的出现 ...

  10. Mybatis insert返回主键ID

    Mybatis insert语句书写 <insert id="insertSelective" useGeneratedKeys="true" keyPr ...