spring bean
@Configuration
public class SpringBean {
@Bean ("dataSource" )
public DriverManagerDataSource driverManagerDataSource (){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver" );
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test" );
dataSource.setUsername("root" );
dataSource.setPassword("123" );
return dataSource;
}
@Bean
public DataSourceTransactionManager dataSourceTransactionManager (DataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean (DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
Resource[] resources = {
new ClassPathResource("mapper/hello.xml" )
};
sqlSessionFactoryBean.setMapperLocations(resources);
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer (){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.example.demo.dal" );
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean" );
return mapperScannerConfigurer;
}
}
mapper/hello.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace ="com.example.demo.dal.HelloDao" >
<select id ="getName" resultType ="java.lang.String" parameterType ="java.lang.Integer" >
SELECT name FROM test WHERE id=#{id} for UPDATE;
</select >
</mapper >
dal
public interface HelloDao {
String getName(@Param("id" ) Integer id);
}
service
@Service
public class HelloService {
@Autowired
public HelloDao helloDao;
@Transactional ("dataSourceTransactionManager" )
public String hello (Integer id){
return helloDao.getName(id);
}
}