wasup
MyBatis Transaction 트랜젝션 Note 본문
반응형
MyBatis 트랜젝션 사용하기!
MyBatisConfig.java
package config;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages= {"com.stone"})
public class MyBatisConfig {
@Bean
public DataSource dataSource() {
String driverClassName="com.mysql.cj.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/mvc2?useUnicode=true";
String username="root";
String password="1234";
//DriverManagerDataSource dataSource=new DriverManagerDataSource();//매번 새로 연결객체구함
BasicDataSource dataSource=new BasicDataSource();//connection pooling지원
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory()throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
return sqlSessionFactoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate()throws Exception{
return new SqlSessionTemplate(sqlSessionFactory());
}
@Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
이하 테스트 파일 준비!
T1Mapper.java
@Mapper
public interface IT1Mapper {
@Insert("insert into t1(col2) values(11)")
void save();
}
T2Mapper.java
@Mapper
public interface IT2Mapper {
@Insert("insert into t2(col3) values(111)")//Errord예정
void save();
}
ITDAO.java
public interface ITDAO {
public void save();
}
ITDAO 상속받아 처리해줄 TDAO 준비
TDAO.java
@Repository("ITDAO1")
public class TDAO implements ITDAO{
@Autowired IT1Mapper t1Mapper;
@Autowired IT2Mapper t2Mapper;
@Override
@Transactional//트랜젝션이 없으면 t1은 입력 t2는 error로 비정상입력이 실행됨.
public void save() {
t1Mapper.save();
t2Mapper.save();//Error예정
}
}
TestController.java
@Controller
public class TestController {
@Autowired @Qualifier("ITDAO1") ITDAO tDAO;
@RequestMapping("do2")
public void process2() {
try {
tDAO.save();
//DAO에 save요청
}
catch(Exception ex) {
System.out.println("process2 정상처리 실패");
ex.printStackTrace();
}
}
}
반응형
'IT > Java' 카테고리의 다른 글
JUnit) unit test!!! (0) | 2021.07.08 |
---|---|
COMMENT 구조 (0) | 2021.06.29 |
spring) file upload (0) | 2021.06.27 |
Spring 시작하기) Note (0) | 2021.06.26 |
JSP) 액션태그 (0) | 2021.06.25 |
Comments