1.第一种构建是使用springboot的方式,
org.springframework.boot spring-boot-starter-web ${spring.boot.version} org.springframework.boot mybatis-spring-boot-starter ${spring.boot.version} org.springframework.boot spring-boot-starter-aop ${spring.boot.version}
spring boot会根据自己的需要引入相对应版本的mybatis
2.第二种,自己引用对应的mybatis版本
org.mybatis mybatis ${mybatis.version} org.mybatis mybatis-spring ${spring.mybatis.version} com.github.pagehelper pagehelper ${mybatis.page.version} com.alibaba druid ${druid.version} mysql mysql-connector-java ${mysql.version}
对应的版本为
1.3.6.RELEASE 1.1.1 3.4.0 1.3.0 1.0.22 5.1.26 4.1.6
通过入口启动内嵌的tomcat,
@SpringBootApplication@ComponentScan(basePackages = "com.capacity")public class BootApp extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(BootApp.class, args); }}
@SpringBootApplication
annotation is equivalent to using @Configuration
, @EnableAutoConfiguration
and @ComponentScan
@ComponentScan组件扫描
下来是mybatis配置:
@Configuration@EnableTransactionManagement@MapperScan("com.capacity.dto")public class MybatisConfig implements TransactionManagementConfigurer { @Autowired DataSource dataSource; @Bean public SqlSessionFactory sqlSessionFactory() { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setTypeAliasesPackage("com.capacity.domain"); PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("reasonable", "true"); properties.setProperty("supportMethodsArguments", "true"); properties.setProperty("returnPageInfo", "check"); properties.setProperty("params", "count=countSql"); pageHelper.setProperties(properties); // 添加插件 bean.setPlugins(new Interceptor[] { pageHelper }); // 添加xml目录 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { bean.setMapperLocations(resolver.getResources("classpath:/mybatis/**/**/*.xml")); return bean.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Bean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); }
可以添加拦截器:
public class WebAppConfig extends WebMvcAutoConfigurationAdapter { public void addInterceptor(InterceptorRegistry registry) { registry.addInterceptor(new UserSecurityInterceptor()).addPathPatterns("/user/**"); }}
这里的配置文件用的是yml格式,不过配置文件好像名字默认是application,不能改,如果要改要用命令行加参数的方式
基本核心代码完了,可以试着建一个dao或者mapper,在建立一个Controller调用一下