一.SpringJDBCTemplate
JDBCTemplate就是Spring对JDBC的封装,通俗点说就是Spring对jdbc的封装的模板。
官方文档:
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html
二.JDBCTemplate测试代码.
直接上代码,具体解释见代码注释
JDBC.java
/*导包,
* spring-test
* spring-aop
* spring-jdbc
* spring-tx
* jdbc驱动
* c3p0连接池:com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
*/
//spring中提供了一个可以操作数据库的对象.对象封装了jdbc技术.
//JDBCTemplate => JDBC模板对象(与DBUtils中的QueryRunner非常相似.)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:cjx/jdbc/jdbc.xml")
public class JDBC {//演示jdbc模板
//纯代码演示
@Test
public void fun1() throws PropertyVetoException{
//1.准备连接池
ComboPooledDataSource dataSource=new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///my");
dataSource.setUser("root");
dataSource.setPassword("cjx");
//2.创建jdbc模板对象
JdbcTemplate jt=new JdbcTemplate();
jt.setDataSource(dataSource);
//3.书写SQL,执行
String sql="insert into user values('465','username','password')";
jt.update(sql);
}
@Resource(name="userDao")
private UserDao ud;
//利用springJDBC模板
@Test
public void fun2(){
//测试保存
// User u=new User();
// u.setId("520");
// u.setUsername("Tom");
// u.setPassword("tomcat");
// ud.save(u);
//测试修改
// User u=new User();
// u.setId("520");
// u.setUsername("TomAAA");
// u.setPassword("tomcatAAA");
// ud.update(u);
//测试删除
// ud.delete("520");
//测试查询总数
// System.out.println(ud.getTotalCount());
//测试查询ById
// System.out.println(ud.getById("123"));
//测试查询所有
System.out.println(ud.getAll());
}
}
User.java
public class User {
private String id;
private String username;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
UserDao.java
public interface UserDao {
//增
void save(User u);
//删
void delete(String id);
//改
void update(User u);
//查
User getById(String id);
//查
int getTotalCount();
//查
List<User> getAll();
}
UserDaoImpl.java
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
private JdbcTemplate jt;//接受jdbc模板对象
/*如果继承JdbcDaoSupport类
* 则不需要手动创建jdbc模板对象
* 直接使用super.getJdbcTemplate()代替即可
* 此处没有使用jdbc模板对象,在配置文件中已经注释掉了
*/
@Override
public void save(User u) {
String sql="insert into user values(?,?,?)";
super.getJdbcTemplate().update(sql, u.getId(),u.getUsername(),u.getPassword());
}
@Override
public void delete(String id) {
String sql="delete from user where id=?";
super.getJdbcTemplate().update(sql,id);
}
@Override
public void update(User u) {
String sql="update user set username=?,password=? where id=?";
super.getJdbcTemplate().update(sql, u.getUsername(),u.getPassword(),u.getId());
}
@Override
public User getById(String id) {
String sql="select * from user where id=?";
return super.getJdbcTemplate().queryForObject(sql, new RowMapper<User>(){
@Override
public User mapRow(ResultSet rs, int index) throws SQLException {
User u=new User();
u.setId(rs.getString("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
return u;
}
}, id);
}
@Override
public int getTotalCount() {
String sql="select count(*) from user ";
return super.getJdbcTemplate().queryForObject(sql, Integer.class);
}
@Override
public List<User> getAll() {
String sql="select * from user";
List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){
@Override
public User mapRow(ResultSet rs, int index) throws SQLException {
User u=new User();
u.setId(rs.getString("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
return u;
}
});
return list;
}
public JdbcTemplate getJt() {
return jt;
}
public void setJt(JdbcTemplate jt) {
this.jt = jt;
}
}
db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///my
jdbc.user=root
jdbc.Password=Password
jdbc.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"
xmlns:aop="http://www.springframework.org/schema/aop"
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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">
<!--配置jdbc -->
<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:cjx/jdbc/db.properties"/>
<!-- 将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="Password" value="${jdbc.Password}"></property>
</bean>
<!-- 将JdbcTemplate放入spring容器 -->
<!--如果继承JdbcDaoSupport类,则不需要注入容器
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
-->
<!-- 将UserDao放入spring容器 -->
<bean name="userDao" class="cjx.jdbc.UserDaoImpl">
<!--如果继承JdbcDaoSupport类,则不需要配置参数
<property name="jt" ref="jdbcTemplate"></property>
-->
<!-- 如果继承JdbcDaoSupport类,只需要注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
三.Transaction测试代码.
直接上代码,具体解释见代码注释
AccountDao.java
public interface AccountDao {//Account账户
//加钱
void addMoney(Integer id,Double money);
//减钱
void dropMoney(Integer id,Double money);
}
AccountDaoImpl.java
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
@Override
public void addMoney(Integer id, Double money) {
getJdbcTemplate().update("update test set money=money+? where id=?",money,id);
}
@Override
public void dropMoney(Integer id, Double money) {
getJdbcTemplate().update("update test set money=money-? where id=?",money,id);
}
}
/*准备表
表名:test
Field Type
id int(11) NOT NULL
name varchar(255) NULL
money double NULL
*/
AccountService.java
public interface AccountService {
//转账方法
void transfer(Integer from,Integer to,Double money);
}
AccountServiceImpl.java
public class AccountServiceImpl implements AccountService {
// private TransactionTemplate tt;//(1)编码式事务管理方式:需要一个模板对象
private AccountDao ad;
@Override
//(3)使用注解配置(aop)spring管理事务方式配置
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
//(3)分别配置隔离级别,传播行为,是否只读。此注解也可以直接加再类上,特殊方法单独使用。
public void transfer(final Integer from, final Integer to, final Double money) {
//减钱
ad.dropMoney(to, money);
// int i=1/0;//制造异常
//加钱
ad.addMoney(from, money);
// // (1)编码式事务管理方式代码:
// tt.execute(new TransactionCallbackWithoutResult() {
// @Override
// protected void doInTransactionWithoutResult(TransactionStatus arg0) {
// // 减钱
// ad.addMoney(from, money);
// // int i=1/0;//制造异常
// // 加钱
// ad.dropMoney(to, money);
// }
// });
}
public AccountDao getAd() {
return ad;
}
public void setAd(AccountDao ad) {
this.ad = ad;
}
// public TransactionTemplate getTt() {
// return tt;
// }
//
// public void setTt(TransactionTemplate tt) {
// this.tt = tt;
// }
}
Transaction.java
/*因为在不同平台,操作事务的代码各不相同.spring提供了一个接口
* PlatformTransactionManager 接口有不同的实现类
* DataSourceTransactionManager:JDBC实现类
* HibernateTransitionmanager:Hibernate实现类
* 在spring中事务管理.最为核心的对象就是TransactionManager对象
*/
/*spring管理事务的属性介绍
* 1.事务的隔离级别(利用数值配置隔离级别)
1 读未提交
2 读已提交
4 可重复读
8 串行化
* 2.是否只读
true 只读
false 可操作
* 3.事务的传播行为(决定业务方法之间调用时,事务如何处理)(7种)
PROPAGATION_REQUIRED--支持当前事务,假设当前没有事务。就新建一个事务。(默认)
PROPAGATION_SUPPORTS--支持当前事务,假设当前没有事务,就以非事务方式运行。
PROPAGATION_MANDATORY--支持当前事务,假设当前没有事务,就抛出异常。
PROPAGATION_REQUIRES_NEW--新建事务,假设当前存在事务。把当前事务挂起。
PROPAGATION_NOT_SUPPORTED--以非事务方式运行操作。假设当前存在事务,就把当前事务挂起。
PROPAGATION_NEVER--以非事务方式运行,假设当前存在事务,则抛出异常。
PROPAGATION_NESTED--假设当前存在事务,则嵌套事务执行。
*/
/*spring管理事务方式
* (1).编码式
1.将核心事务管理器配置到spring容器
2.配置TransactionTemplate模板
3.将事务模板注入Service
4.在Service中调用模板
* (2).xml配置(aop)
1.导包
2.导入新的约束(tx)
3.配置通知
4.配置将通知织入目标
* (3).注解配置(aop)
1.导包
2.导入新的约束(tx)
3.开启注解管理事务
4.使用注解
*/
@RunWith(SpringJUnit4ClassRunner.class)
//(1).编码式(已注释,无演示)|(2).xml配置(演示)spring管理事务方式配置文件
@ContextConfiguration("classpath:cjx/transaction/transaction.xml")
//(3).注解配置(演示)spring管理事务方式配置文件
//@ContextConfiguration("classpath:cjx/transaction/transactionAnnotate.xml")
public class Transaction {
@Resource(name="accountService")
private AccountService as;
@Test
public void fun(){
as.transfer(1, 2, 100d);
}
}
db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///my
jdbc.user=root
jdbc.Password=Password
transaction.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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:cjx/jdbc/db.properties"/>
<!-- 将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="Password" value="${jdbc.Password}"></property>
</bean>
<!-- 事务核心管理器(transactionManager),封装了所有事务操作,依赖于连接池-->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--(1)编码式spring事务管理方式配置 -->
<!-- (1)配置事务模板对象transactionTemplate
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property>
</bean>
-->
<!--(2)xml配置(aop)spring管理事务方式配置
需要导入新约束http://www.springframework.org/schema/tx/spring-tx-4.2.xsd-->
<!-- (2)配置事务通知 -->
<!-- (2)以方法为单位,指定方法应用什么事务属性.
name:方法名,可以使用*通配符
isolation:隔离级别
propagation:传播行为
read-only:是否只读 -->
<!-- (2)这里使用了通配符* ,只要方法名以tran开头,就会使用此策略 -->
<!-- (2)使用通配符* ,可以减少配置量,只要以指定的名称开头即可-->
<tx:advice id="txAdivce" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="tran*" isolation="DEFAULT" propagation="REQUIRED" read-only="false" />
</tx:attributes>
</tx:advice>
<!-- (2)配置织入目标对象 -->
<aop:config>
<!-- (2)配置切点表达式-->
<aop:pointcut expression="execution(* cjx.transaction.*ServiceImpl.*(..))" id="txpc"/>
<!-- (2)配置切面:通知(advice-ref)+切点(pointcut-ref)-->
<aop:advisor advice-ref="txAdivce" pointcut-ref="txpc"/>
</aop:config>
<!--(3)注解配置(aop)spring管理事务方式配置
详情见配置文件transactionAnnotate.xml
-->
<!-- 将Dao放入spring容器 -->
<bean name="accountDao" class="cjx.transaction.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 将Service放入spring容器 -->
<bean name="accountService" class="cjx.transaction.AccountServiceImpl">
<property name="ad" ref="accountDao"></property>
<!-- (1)编码式事务管理方式注入事务模板对象
<property name="tt" ref="transactionTemplate"></property>
-->
</bean>
</beans>
transactionAnnotate.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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:cjx/jdbc/db.properties"/>
<!-- 将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="Password" value="${jdbc.Password}"></property>
</bean>
<!-- 事务核心管理器(transactionManager),封装了所有事务操作,依赖于连接池-->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--(3)注解配置(aop)spring管理事务方式配置
需要导入新约束http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
-->
<!-- (3)开启使用注解管理aop事务 -->
<!--(3)在需要开启事务的方法上使用注解标识即可 -->
<tx:annotation-driven/>
<!-- 将Dao放入spring容器 -->
<bean name="accountDao" class="cjx.transaction.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 将Service放入spring容器 -->
<bean name="accountService" class="cjx.transaction.AccountServiceImpl">
<property name="ad" ref="accountDao"></property>
</bean>
</beans>