最近学习了下Spring JDBC的一些基本用法,故做此总结。
不知道该如何写这篇总结,稍微汇总下本次学习的源代码,未来可能会用上。
Spring JDBC的配置是在XML文件中进行的,配置一定需要连接成功。查询,更新数据都很常规,下面也提供了这些。
另外,NamedParameterJdbcTemplate具名参数是个非常好用的类,当表的列过多的时候,具名参数是个不错的选择。
db.properties配置文件
username=root password=root driverClass=com.mysql.jdbc.Driver JdbcUrl=jdbc:mysql://127.0.0.1:3307/hello initPoolSize=5 maxPoolSize=10
<?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:component-scan base-package="com.spring.jdbc.test1"></context:component-scan> <!-- 导入资源文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 配置c3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${username}"></property> <property name="password" value="${password}"></property> <property name="jdbcUrl" value="${JdbcUrl}"></property> <property name="driverClass" value="${driverClass}"></property> <property name="numHelperThreads" value="10"></property> <property name="initialPoolSize" value="${initPoolSize}"></property> <property name="maxPoolSize" value="${maxPoolSize}"></property> </bean> <!-- 配置JDBCTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置NamedParameterJdbcTemplate --> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource"></constructor-arg> </bean> </beans>
package com.spring.jdbc.test1; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; @Repository public class StudentDao { @Autowired private JdbcTemplate jdbcTemplate; public Student get(Integer ID) { String sql = "select * from Student where id = ?"; Student student = null; RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>( Student.class); student = jdbcTemplate.queryForObject(sql, rowMapper, ID); return student; } }
package com.spring.jdbc.test1; public class Student { private Integer id; private String name; private String sex; private Integer grade; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Integer getGrade() { return grade; } public void setGrade(Integer grade) { this.grade = grade; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", grade=" + grade + "]"; } }
package com.spring.jdbc.test1; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.junit.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 org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; public class JDBCTest { private ApplicationContext ctx = null; private JdbcTemplate jdbcTemplate = null; private StudentDao studentDao = null; private NamedParameterJdbcTemplate namedParameterJdbcTemplate = null; { ctx = new ClassPathXmlApplicationContext("spring-jdbc.xml"); jdbcTemplate = ctx.getBean(JdbcTemplate.class); studentDao = ctx.getBean(StudentDao.class); namedParameterJdbcTemplate = ctx.getBean(NamedParameterJdbcTemplate.class); } /** * 测试数据库是否连接上 * * @throws SQLException */ @Test public void testDataSource() throws SQLException { System.out.println("hehe"); DataSource datasource = (DataSource) ctx.getBean("dataSource"); System.out.println(datasource.getConnection()); } /** * 执行批量更新,插入数据 */ @Test public void testBatchUpdate() { String sql = "insert into Student value(?,?,?,?)"; List<Object[]> list = new ArrayList<>(); list.add(new Object[] { 3, "Ny", "F", "11" }); list.add(new Object[] { 4, "N", "F", "20" }); list.add(new Object[] { 5, "Nay", "F", "12" }); list.add(new Object[] { 6, "Nqaancy", "F", "130" }); list.add(new Object[] { 7, "Nncq1y", "F", "110" }); list.add(new Object[] { 8, "Nancysw", "F", "10" }); jdbcTemplate.batchUpdate(sql, list); } /** * 修改数据 * * @throws SQLException */ @Test public void testJDBCUpdate() throws SQLException { String sql = "UPDATE Student set grade=? where id=?"; System.out.println("111"); System.out.println(jdbcTemplate.update(sql, 10, 2)); } /** * 查询数据,并且赋值给对象,通过结果输出结果,jdbcTemplate.queryForObject(sql1, rowMapper) * 的返回值仅仅是一个对象 */ @Test public void testQueryForObject() { String sql1 = "select * from Student where id = 2"; String sql2 = "select * from Student where id = ?"; RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>( Student.class); Student student1 = jdbcTemplate.queryForObject(sql1, rowMapper); Student student2 = jdbcTemplate.queryForObject(sql2, rowMapper, 1); System.out.println(student1); System.out.println(student2); } /** * 查询到的结果是一个集合 */ @Test public void testQueryList() { String sql = "select * from Student"; RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>( Student.class); List<Student> listOfStudent = jdbcTemplate.query(sql, rowMapper); System.out.println(listOfStudent); } /** * 统计查询,获取单列值 */ @Test public void testQueryNumber() { String sql = "select count(id) from Student"; Integer num = jdbcTemplate.queryForObject(sql, Integer.class); System.out.println(num); } /** * 测试StudentDao 测试通过 */ @Test public void testStudentDao() { Student student = studentDao.get(2); System.out.println(student); } /** * 测试NamedParameterJdbcTemplate * 好处:便于维护,可以给变量起名字 * 缺点:较为麻烦 */ @Test public void testNamedParameterJdbcTemplate(){ String sql="insert into Student value(:id,:name,:sex,:grade)"; Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("id", 100); paramMap.put("name", "Hello"); paramMap.put("sex", "M"); paramMap.put("grade", 1000); namedParameterJdbcTemplate.update(sql, paramMap); } /** * 测试namedParameterJdbcTemplate的另一种使用方式 */ @Test public void testNamedParameterJdbcTemplate2(){ String sql="insert into Student value(:id,:name,:sex,:grade)"; Student student = new Student(); student.setGrade(1000); student.setId(34); student.setName("HEHEHEH"); student.setSex("W"); SqlParameterSource paramSource = new BeanPropertySqlParameterSource(student); namedParameterJdbcTemplate.update(sql, paramSource); } }