文章目录
- spring提供了很多模板整合Dao技术
- spring中提供了一个可以操作数据库的对象.对象封装了jdbc技术.
- 如何用Spring中的jdbc模板对数据库操作:
- spring配置
- 进阶内容
- JDBCDaoSupport的使用
spring提供了很多模板整合Dao技术
因为在jdbc、Hibernate、Mybatis中都有对数据库封装好方法,但是不同的框架中方法名称都不相同,为了方便开发者调用和整理代码,Spring中提供了很多模板来整合Dao技术
spring中提供了一个可以操作数据库的对象.对象封装了jdbc技术.
JDBCTemplate => JDBC模板对象
其实Spring的JDBCTemplate有点像DBUtils与DBUtils中的QueryRunner非常相似.,但是有时候还没有DBUitls好用。
代码模板:
ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass("com.mysql.jdbc.Driver");//jdbc:mysql:///jdbcTest表示默认加载本地localhost dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/jdbcTest");dataSource.setUser("root");dataSource.setPassword("1234");JdbcTemplate template = new JdbcTemplate();template.setDataSource(dataSource);String mysql="insert into userdemo values('alan',18,null) ";template.update(mysql);
如何用Spring中的jdbc模板对数据库操作:
- 导包:4+2+ :spring-test 、spring-aop 、 junit4类库 、 c3p0连接池 、JDBC驱动 、spring-jdbc 、 spring-tx事务
- 准备数据库
3.书写Dao
增删改:
查询单个对象
查询值类型
查询List集合类型
spring配置
依赖关系
画依赖关系图是为了Spring配置做铺垫
Spring中的配置代码
配置数据库连接池方法用法:
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.jdbc.Driver"></property><property name="jdbcUrl" value="jdbc:mysql:///jdbctest"></property><property name="user" value="root"></property><property name="password" value="1234"></property>
</bean>
为了防止每次修改数据库连接池里面配置的参数都需要打开xml文件,可以把参数写在properties文件中,然后在xml中调用的时候用${key名字}
读取外部的Properties配置:
jdbc.jdbcUrl=jdbc:mysql:///hibernate_32
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=1234
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd "><!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties" /><!-- 1.将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" ><property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property><property name="driverClass" value="${jdbc.driverClass}" ></property><property name="user" value="${jdbc.user}" ></property><property name="password" value="${jdbc.password}" ></property>
</bean><!-- 2.将JDBCTemplate放入spring容器 -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" ><property name="dataSource" ref="dataSource" ></property>
</bean><!-- 3.将UserDao放入spring容器 -->
<bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" ><!-- <property name="jt" ref="jdbcTemplate" ></property> --><property name="dataSource" ref="dataSource" ></property>
</bean></beans>
练习代码:
存储的对象:
package com.jdbc.learn;public class User {String name;Integer age;Integer id;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}}
UserDaoImpl实现类
package com.jdbc.learn;import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;public class UserDaoImpl implements UserDao {private JdbcTemplate jdbcTemplate;public JdbcTemplate getJdbcTemplate() {return jdbcTemplate;}public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;}public void save(User user) {String sql = "insert into userdemo value(?,?,null)";jdbcTemplate.update(sql, user.getName(), user.getAge());}}
测试类:
package com.jdbc.learn;import javax.annotation.Resource;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:com/jdbc/learn/applicationContext.xml")
public class JdbcDemo {@Resource(name="userDao")private UserDao userDao ;@Testpublic void fun22(){User user = new User();user.setAge(18);user.setName("weijie");userDao.save(user);}
}
进阶内容
JDBCDaoSupport的使用
在实现方法中继承JDBCDaoSupport类,这样在调用JdbcTemplate时候不需要去new JdbcTemplate的对象再去调用里面的方法,直接通过super父类中的方法获取对象:super.getJdbcTemplate(),注意在容器中配置的时候就不需要将template放入容器中,然后把dataSource指向userDao类中
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd "><!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties" /><!-- 1.将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" ><property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property><property name="driverClass" value="${jdbc.driverClass}" ></property><property name="user" value="${jdbc.user}" ></property><property name="password" value="${jdbc.password}" ></property>
</bean><!-- 2.将JDBCTemplate放入spring容器 -->
<!-- <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" ><property name="dataSource" ref="dataSource" ></property>
</bean> --><!-- 3.将UserDao放入spring容器 -->
<bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" ><!-- <property name="jt" ref="jdbcTemplate" ></property> --><property name="dataSource" ref="dataSource" ></property>
</bean></beans>
UserDao接口
package com.jdbc.learn;public interface UserDao {void save(User user);}
UserDao
package cn.itcast.a_jdbctemplate;import java.util.List;import cn.itcast.bean.User;public interface UserDao {//增void save(User u);//删void delete(Integer id);//改void update(User u);//查User getById(Integer id);//查int getTotalCount();//查List<User> getAll();
}
UserDaoImpl
package cn.itcast.a_jdbctemplate;import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;import cn.itcast.bean.User;
//使用JDBC模板实现增删改查
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {@Overridepublic void save(User u) {String sql = "insert into t_user values(null,?) ";super.getJdbcTemplate().update(sql, u.getName());}@Overridepublic void delete(Integer id) {String sql = "delete from t_user where id = ? ";super.getJdbcTemplate().update(sql,id);}@Overridepublic void update(User u) {String sql = "update t_user set name = ? where id=? ";super.getJdbcTemplate().update(sql, u.getName(),u.getId());}@Overridepublic User getById(Integer id) {String sql = "select * from t_user where id = ? ";return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){@Overridepublic User mapRow(ResultSet rs, int arg1) throws SQLException {User u = new User();u.setId(rs.getInt("id"));u.setName(rs.getString("name"));return u;}}, id);}@Overridepublic int getTotalCount() {String sql = "select count(*) from t_user ";Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);return count;}@Overridepublic List<User> getAll() {String sql = "select * from t_user ";List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){@Overridepublic User mapRow(ResultSet rs, int arg1) throws SQLException {User u = new User();u.setId(rs.getInt("id"));u.setName(rs.getString("name"));return u;}});return list;}}
测试类:
package cn.itcast.a_jdbctemplate;import java.beans.PropertyVetoException;import javax.annotation.Resource;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.mchange.v2.c3p0.ComboPooledDataSource;import cn.itcast.bean.User;//演示JDBC模板
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {@Resource(name="userDao")private UserDao ud;@Testpublic void fun1() throws Exception{//0 准备连接池ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass("com.mysql.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql:///hibernate_32");dataSource.setUser("root");dataSource.setPassword("1234");//1 创建JDBC模板对象JdbcTemplate jt = new JdbcTemplate();jt.setDataSource(dataSource);//2 书写sql,并执行String sql = "insert into t_user values(null,'rose') ";jt.update(sql);}@Testpublic void fun2() throws Exception{User u = new User();u.setName("tom");ud.save(u);}@Testpublic void fun3() throws Exception{User u = new User();u.setId(2);u.setName("jack");ud.update(u);}@Testpublic void fun4() throws Exception{ud.delete(2);}@Testpublic void fun5() throws Exception{System.out.println(ud.getTotalCount());}@Testpublic void fun6() throws Exception{System.out.println(ud.getById(1));}@Testpublic void fun7() throws Exception{System.out.println(ud.getAll());}}