这里没写目录标题!!!
JdbcTemplate概述:
JdbcTemplate是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。spring框架为我们提供了更多的操作类模板。
例如:操作关系型数据的JdbcTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操作消息队列的JmsTemplate等等。
JdbcTemplate开发步骤:
1.导入spring-jdbc和spring-tx坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
2.创建数据库表和实体
CREATE TABLE account(
NAME VARCHAR(30),
money INT(10)
);
public class Account {
private String name;
private double money;
}
3.创建JdbcTemplate对象
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
4.执行数据库操作
@Test
//测试JdbcTemplate
public void test1() throws PropertyVetoException {
//创建数据源对象
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("root");
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//设置数据源对象:知道数据库在哪
jdbcTemplate.setDataSource(dataSource);
//执行操作
int row = jdbcTemplate.update("insert into account values(?,?)", "tom", 50);
System.out.println(row);
}
Spring产生JdbcTemplate对象
将JdbcTemplate和DataSource的创建权交给spring,在Spring容器内部将DataSource注入到JdbcTemplate模板对象中
<!-- 数据源对象-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///test"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
@Test
//测试spring产生JdbcTemplate对象
public void test2() throws PropertyVetoException {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate=app.getBean(JdbcTemplate.class);
int row=jdbcTemplate.update("insert into account values(?,?)","zhangsan",40);
System.out.println(row);
}
抽取数据源对象时jdbc.properties配置:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
之后加载jdbc.properties,配置数据源
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 数据源对象-->
<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>
</bean>
其他数据库操作
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
//修改测试
public void testUpdate() {
jdbcTemplate.update("update account set money=? where name=?", 60, "tom");
}
@Test
//删除测试
public void testDelete() {
jdbcTemplate.update("delete from account where name=?", "tom");
}
@Test
//查询测试
public void testQueryAll() {
List<Account> accountList = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
System.out.println(accountList);
}
@Test
//单个查询测试
public void testQueryOne() {
Account account = jdbcTemplate.queryForObject("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), "zhangsan");
System.out.println(account);
}
@Test
//聚合查询测试
public void testQueryCount() {
Long count=jdbcTemplate.queryForObject("select count(*) from account",long.class);
System.out.println(count);
}
编程式事务控制相关对象
1.PlatformTransactionManager接口
PlatformTransactionManager接口是spring的事务管理器,它提供了常用的操作事务的方法:
- TransactionStatus getTransation(TransacttionDefination defination):获取事务的状态信息
- void commit(TransactionStatus status):提交事务
- void rollback(TransactionStatus status):回滚事务
2.TransactionDefinition
TransactionDefinition是事务的定义信息对象,里面的方法:
- int getIsolationLevel():获得事务的隔离级别
- int getPropogationBehavior():获得事务的传播行为
- int getTimeout():获得超时时间
- boolean isReadOnly():是否只读
事务隔离级别:可以解决事务并发产生的脏读、不可重复读和幻读:
ISOLATION_DEFAULT
ISOLATION_READ_UNCOMMITTED
ISOLATION_READ_COMMITTED
ISOLATION_REPEATABLE_READ
ISOLATION_SERIALIZABLE
事务传播行为:
REQUIRED:如果当前没有事务,就新建一个事务,如果有,就加入这个事务(默认)
SUPPORTS:支持当前事务,如果没有,就以非事务方式执行
MANDATORY:使用当前事务,如果没有,则抛出异常
REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,把当前事务挂起
NEVER:以非事务方式运行,如果当前存在事务,抛出异常
NESTED:如果当前存在事务,则在嵌套事务内执行;如果当前没有事务,则执行REQUIRED类似的操作
超时时间:默认值是-1,没有超时限制,如果有,设置单位为秒
是否只读:建议查询时设置为只读
3.TransactionStatus接口
TransactionStatus接口提供的是事务具体的运行状态,方法如下:
boolean hasSavepoint():是否存储回滚点
boolean isCompleted():事务是否完成
boolean isNewTransaction():是否是新事物
boolean isRollbackOnly():事务是否回滚
声明式事务控制
声明式事务控制:采用声明的方式来处理业务
声明式事务处理的作用:
- 事务管理不侵入开发的组件
- 在不需要事务管理的时候,只要修改设定的文件,即可移去事务管理服务
Spring声明式事务控制底层就是AOP
基于XML的声明式事务控制
配置文件:
<!-- 加载jdbc.propertiex-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 数据源对象-->
<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>
</bean>
<!-- JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="accountDao" class="com.itzhuo.dao.impl.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<!-- 目标对象 内部的方法就是切点-->
<bean id="accountService" class="com.itzhuo.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<!-- 配置平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 通知 事务的增强-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务的aop织入-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itzhuo.service.impl.*.*(..))"></aop:advisor>
</aop:config>
其中事务增强配置参数:
<tx:method name=“transfer” isolation=“REPEATABLE_READ” propagation=“REQUIRED” timeout="-1" read-only=“false”/>
name:切点方法名称
isolation:事务的隔离级别
propogation:事务的传播行为
timeout:超时时间
read-only:是否只读
Dao层:
public class AccountDaoImpl implements AccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void out(String outMan, double money) {
jdbcTemplate.update("update account set money=money-? where name=?", money, outMan);
}
public void in(String inMan, double money) {
jdbcTemplate.update("update account set money=money+? where name=?", money, inMan);
}
}
Service层
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao){
this.accountDao=accountDao;
}
public void transfer(String outMan,String inMan,double money){
accountDao.out(outMan, money);
accountDao.in(inMan,money);
}
}
数据类:
public class Account {
private String name;
private int money;
}
测试:
public class AccountController {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService=app.getBean(AccountService.class);
accountService.transfer("zhangsan","lisi",10);
}
}
基于注解的声明式事务控制
配置文件:
<!-- 组件扫描-->
<context:component-scan base-package="com.itzhuo"/>
<!-- 加载jdbc.propertiex-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 数据源对象-->
<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>
</bean>
<!-- JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 事务的注解驱动-->
<tx:annotation-driven transaction-manager="transactionManager"/>
与上例的不同:
* 删除Dao、Srevice层路径
* 删除通知、配置事务的aop织入
* 添加组件扫描、事务的注解驱动
Dao层:
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void out(String outMan, double money) {
jdbcTemplate.update("update account set money=money-? where name=?", money, outMan);
}
public void in(String inMan, double money) {
jdbcTemplate.update("update account set money=money+? where name=?", money, inMan);
}
}
Service层
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
public void transfer(String outMan,String inMan,double money){
accountDao.out(outMan, money);
// int i=1/0;
accountDao.in(inMan,money);
}
}
测试:
public class AccountController {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService=app.getBean(AccountService.class);
accountService.transfer("zhangsan","lisi",10);
}
}