1.搭建和配置Spring与JDBC整合的环境
项目工程图:
使用Spring+JDBC集成步骤如下:
【第一步】、创建一个简单java工程,如:spring-03-jdbc
【第二步】、导包
使用c3p0数据源
【第三步】、添加数据库配置文件db.properties
db.properties内容为:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
username=root
password=root
jdbc.initPoolSize=5
jdbc.maxPoolSize=10
【第四步】、添加spring配置文件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" />
<!-- 配置c3p0数据源 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
</beans>
【第五步】、在com.zzc.jdbc包下创建一个测试类JDBCTest
JDBCTest.java:
public class JDBCTest {
private ApplicationContext ctx = null;
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void test() throws SQLException {
DataSource dataSource = (DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());
}
}
【第六步】、引入spring中的jdbcTemplate
修改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" />
<!-- 配置c3p0数据源 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></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>
【第七步】、测试
修改JDBCTest类,添加更新/增加/删除方法:
public class JDBCTest {
private ApplicationContext ctx = null;
private JdbcTemplate jdbcTemplate = null;
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
}
@Test
public void testUpdate() {
String sql = "UPDATE user SET name = ? WHERE id = ?";
jdbcTemplate.update(sql, "张三", 6);
}
@Test
public void test() throws SQLException {
DataSource dataSource = (DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());
}
}
执行此条语句可能会报错:jdbcTemplate.update(sql, “张三”, 6);
需要添加spring-tx-4.0.0.RELEASE.jar包
添加查询一个对象方法:
@Test
public void testQuery() {
String sql = "SELECT * FROM user WHERE id = ?";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
User user = jdbcTemplate.queryForObject(sql, rowMapper, 1);
System.out.println(user);
}
- RowMapper:指定如何去映射结果集的行
添加查询多个对象方法:
@Test
public void testQueryList() {
String sql = "SELECT * FROM user";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
List<User> users = jdbcTemplate.query(sql, rowMapper);
System.out.println(users);
}
添加获取单列的值的方法:
@Test
public void testCount() {
String sql = "SELECT COUNT(*) FROM user";
long count = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count);
}
2.dao层使用jdbcTemplate
创建一个com.zzc.dao包,在其下创建一个UserDao类
UserDao.java
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate = null;
public User queryUserById(Integer id) {
String sql = "SELECT * FROM user WHERE id = ?";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
User user = jdbcTemplate.queryForObject(sql, rowMapper, 1);
return user;
}
}
由于使用了@Repository注解,所以还需要在applicationContext.xml配置文件开启此注解支持。这样UserDao就注册到IOC容器中了
需要添加以下内容:
<context:component-scan base-package="com.zzc.dao"></context:component-scan>
测试方法:
JDBCTest.java
public class JDBCTest {
private ApplicationContext ctx = null;
private JdbcTemplate jdbcTemplate = null;
private UserDao userDao = null;
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
userDao = ctx.getBean(UserDao.class);
}
@Test
public void testDaoQuery() {
User user = userDao.queryUserById(1);
System.out.println(user);
}
...
}
userDao = ctx.getBean(UserDao.class); : 从容器中获取UserDao
3.NamedParameterJdbcTemplate
在applicationContext.xml中配置NamedParameterJdbcTemplate
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
该NamedParameterJdbcTemplate对象可以使用具名参数,其没有无参构造器,必须为其构造器指定参数
- 在经典的 JDBC 用法中, SQL 参数是用占位符 ? 表示,并且受到位置的限制. 定位参数的问题在于, 一旦参数的顺序发生变化, 就必须改变参数绑定.
- 在 Spring JDBC 框架中, 绑定 SQL 参数的另一种选择是使用具名参数(named parameter).
具名参数: SQL 按名称(以冒号开头)而不是按位置进行指定. 具名参数更易于维护, 也提升了可读性. 具名参数由框架类在运行时用占位符取代
JDBCTest.java
private NamedParameterJdbcTemplate namedParameterJdbcTemplate = null;
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
namedParameterJdbcTemplate = ctx.getBean(NamedParameterJdbcTemplate.class);
}
@Test
public void testNamedParameterJdbcTemplate() {
String sql = "INSERT INTO user VALUES (NULL, :na, :sex, :email)";
Map<String, Object> map = new HashMap<String, Object>();
map.put("na", "AAAA");
map.put("sex", 1);
map.put("email", "[email protected]");
namedParameterJdbcTemplate.update(sql, map);
}
为参数起名字。
好处:若有多个参数,则再不用去对应位置,直接对应参数名,便于维护
坏处:较为麻烦
若实体类属性与数据库字段一致,则可以使用sqlParameterSource参数
@Test
public void testNamedParameterJdbcTemplate2() {
String sql = "INSERT INTO user VALUES (NULL, :name, :sex, :email)";
User u = new User();
u.setName("BBBB");
u.setSex(0);
u.setEmail("[email protected]");
SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(u);
namedParameterJdbcTemplate.update(sql, sqlParameterSource);
}