Springoo

springboot+mybatis 整合以及AOP拦截器,事物

2018-05-06  本文已影响1024人  阿__飞

1.创建 springboot+mybatis 应用

2.pom 文件的编写,需要配置相关数据库连接

3.配置 mybatis-config 文件

4.配置 datasource 

@Configuration // 配置 mybatis mapper 的扫描路径 @MapperScan("com.qinmei.demo.dao") public class DataSourceConfiguration { @Value("${jdbc.driver}") private String jdbcDriver; @Value("${jdbc.url}") private String jdbcUrl; @Value("${jdbc.username}") private String jdbcPassword; @Value("${jdbc.password}") private String jdbcUsername; @Bean(name = "dataSource") public ComboPooledDataSource createDataSource() throws PropertyVetoException { // 数据库连接池的配置 ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass(jdbcDriver); dataSource.setJdbcUrl(jdbcUrl); dataSource.setUser(jdbcUsername); dataSource.setPassword(jdbcPassword); // 关闭连接后不自动 commit提交 dataSource.setAutoCommitOnClose(false); return dataSource; } }

5.配置 sessionFactory

@Configuration public class SessionFactoryConfiguration { // mybatis-config.xml 配置文件的路径 @Value("${mybatis_config_file}") private String mybatisConfigFilePath; // mybatis mapper 文件所在路径 @Value("${mapper_path}") private String mapperPath; // 实体类所在的 package @Value("${entity_package}") private String entityPackage; @Autowired  //按照名称加载 datasource @Qualifier("dataSource") private DataSource dataSource; @Bean(name = "sqlSessionFactory") public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException { // 创建 sqlSession 工厂 SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath)); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // mapper 文件存放的位置 String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath; // 设置属性 sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath)); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage); return sqlSessionFactoryBean; } }

6.配置文件

server.port=80 server.context-path=/demo # 数据库连接 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/demo jdbc.username=root jdbc.password=root #Mybatis mybatis_config_file=mybatis-config.xml mapper_path=/mapper/**.xml entity_package=com.qinmei.demo.entity

7.dao层编写接口

8.dao 层 mapper 编写

9.dao 层测试

测试自动注入时会报错,找不到实例,修改 idea 配置即可

10.service 层事物配置

11.service 层编写

12.conroller 层实现

13.统一异常处理

14.自定义异常类(扩展)

a.编写自定义异常类

b.异常处理进行判断

c.表单验证   

import javax.persistence.Entity; 

import javax.persistence.GeneratedValue; 

import javax.persistence.Id; 

import javax.validation.constraints.Min;

15.AOP拦截器

16.配置文件的 yml 格式

上一篇下一篇

猜你喜欢

热点阅读