Spring的jdbc支持
1配置db.properties,将有关JDBC的信息载入
2bean文件配置数据源,这里用e3p0作为数据源载入db.properties
3配置template的bean 之后,可以直接使用。
JUnit的测试
代码如下
db.proeprties
jdbc.username=root
jdbc.password=s1127736971
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/school
jdbc.iniPoolSize=5
jdbc.maxPoolSize=10
//强烈注意!!!!! 每行空格也要删掉,因为载入的时候会读取空格
bean文件如下
<?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.1.xsd"> <!-- 配置配置文件 -->
<context:property-placeholder location="classpath:db.properties"/> <!-- 配置数据源文件 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="initialPoolSize" value="${jdbc.iniPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean> <!-- 配置template -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> <context:component-scan base-package="Test"></context:component-scan>
</beans>
java文件如下
package Test; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; 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; public class test {
private ApplicationContext ctx= null;
private JdbcTemplate jdbcTemplate=null;
private StudentDao dao;
{
ctx=new ClassPathXmlApplicationContext("SpringJDBC.xml");
jdbcTemplate=(JdbcTemplate) ctx.getBean("jdbcTemplate");//里面就已经配置了datasource的配置,所以可以更改。
dao=ctx.getBean(StudentDao.class);
} @Test
public void testStudentDao(){
System.out.println(dao.getById(2));
} @Test
public void testQueryForObject(){//用于数据统计类型
String sql = "SELECT COUNT(id) FROM student ";
long count = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count); } @Test
public void testQueryForList(){//收集属性集合类型
String sql = "SELECT id,name,age,address FROM student WHERE id>? ";
RowMapper<Student> rowMapper= new BeanPropertyRowMapper<Student>(Student.class);
List<Student> students =jdbcTemplate.query(sql, rowMapper,1);//一个不同的集合语句
System.out.println(students); } /*
* 这里要用BeanPropertyRowMapper,不要在queryForObject里面用另一个,格式如下。
* 1 可以在里面配置类对应的名字,比如 name name 前一个是类属性名字,后一个是database里面名字
* 2 不支持级联属性
* 3 RowMapper 是映射属性行,BeanPropertyRowMapper是其一个实现类
* */
@Test
public void testQueryById(){
String sql = "SELECT id,name,age,address FROM student WHERE id=? ";
RowMapper<Student> rowMapper= new BeanPropertyRowMapper<Student>(Student.class);
Student student =jdbcTemplate.queryForObject(sql, rowMapper,1);
System.out.println(student);
} @Test
public void testUpdateBatch(){
String sql = "INSERT INTO student(id,name,age,address) Values(?,?,?,?)";
List<Object[]> date = new ArrayList<>();
date.add(new Object[]{"5","xiaohong","52","shanghai"});
date.add(new Object[]{"6","xiaobai","22","fujian"});
jdbcTemplate.batchUpdate(sql, date); } @Test//这个更新可以是 UPDATE DELETE INSERT
public void testUpdate (){
String sql = "UPDATE student SET Address = ? where id=?";
jdbcTemplate.update(sql, "beijing",4);
} @Test
public void testDataSource() throws SQLException {//测试 DataSource是否可行
DataSource datasource = (DataSource) ctx.getBean(javax.sql.DataSource.class);//记一个非常不科学的错误,db.properties里面不要有空格,他会把空格也当成命令。
System.out.println(datasource.getConnection());
} }
注,一般用Dao类文件,是将Dao里面添加jdbcTemplate成员属性。而不用另一种extends 的方法,不考虑。
package Test; 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 getById(int id){
String sql = "SELECT id,name,age,address FROM student WHERE id=? ";
RowMapper<Student> rowMapper= new BeanPropertyRowMapper<Student>(Student.class);
Student student =jdbcTemplate.queryForObject(sql, rowMapper,id);
return student;
}
}
使用jdbc的具名参数设置
配置NamedParameterJdbcTemplate Bean文件
xml添加
<!-- 配置带参template -->
<bean id="namedtemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
java代码添加测试
@Test//这是利用对象来具名参数,要求Values(:id,:name,:age,:address)和类的名字要一样,mysql的名字要一样。
public void testNamedTemplate2(){
String sql = "INSERT INTO student(id,name,age,address) Values(:id,:name,:age,:address)";
Student student = new Student();
student.setId(11);
student.setAge(4);
student.setName("xiaoxiaobai");
student.setAddress("hong shang lu ");
SqlParameterSource ss = new BeanPropertySqlParameterSource(student);
namedParameterJdbcTemplate.update(sql, ss);
} @Test//利用具名参数来构造template 优点当参数多的时候维护比较容易 不需要按照固定顺序。缺点是相对于estUpdateBatch()比较复杂
public void testNamedTemplate(){
String sql = "INSERT INTO student(id,name,age,address) Values(:id,:name,:age,:address)";
Map<String,Object> paramMap = new HashMap<String,Object>();
paramMap.put("id", 10);
paramMap.put("name", "xiaobai");
paramMap.put("age",51 );
paramMap.put("address", "tongbei");
namedParameterJdbcTemplate.update(sql, paramMap);
}