事务使用java config 开启可以这样写:
事务只需要注入getDataSourceTransactionManager这个bean,并且加上@EnableTransactionManagement即可。这里用了阿里的德鲁克的数据源。
package com.max;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan(value = "com.max")
@EnableTransactionManagement
public class MaxConfig {
@Bean
public JdbcTemplate getJdbcTemplate(){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(getDruidDataSource());
return jdbcTemplate;
}
@Bean
public DruidDataSource getDruidDataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUsername("root");
druidDataSource.setPassword("123456");
druidDataSource.setUrl("jdbc:mysql://localhost:3306/test");
druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
return druidDataSource;
}
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(getDruidDataSource());
return dataSourceTransactionManager;
}
}
如何使用呢,在DAO层直接使用@Autowrid注入即可
@Repository
public class UserDaoImpl implements IUserDao{
@Autowired
private JdbcTemplate jdbcTemplate1;
@Override
public List<User> getUser(){
return jdbcTemplate1.query("select * from oooo where id =1 ",new BeanPropertyRowMapper<>(User.class));
}
@Override
public void add(){
jdbcTemplate1.update("update oooo set age = 10 where id = 1");
}
@Override
public void reduce(){
jdbcTemplate1.update("update oooo set age = 10 where id = 3");
}
}
使用事务,在service层,加上@Transactional注解即可
package com.max.service.impl;
import com.max.dao.IUserDao;
import com.max.entity.User;
import com.max.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao iUserDao;
public List<User> getUser(Integer id){
List<User> user = iUserDao.getUser();
return user;
}
public void add (){
iUserDao.add();
}
public void reduce(){
iUserDao.reduce();
}
@Transactional
public void test(){
add();
int i = 1/0;
reduce();
}
}