Spring-Mybatis
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。 最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring
一、SpringBoot-Mybatis
1、jar包依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
2、application.properties中配置数据库连接信息
#数据库信息 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=yang spring.datasource.password=yang # mapper xml文件路径 mybatis.mapper-locations=classpath:mapper/*Mapper.xml
3、启动类上添加MapperScan注解,扫描Mapper接口
import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan(basePackages = "com.yang.spbo.mybatis.mapper") @SpringBootApplication public class SpboMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpboMybatisApplication.class, args); } }
4、定义Mapper接口,@Mapper注解可省略
@Mapper public interface WeiboFansMapper { int insertWeiboFans(WeiboFans weiboFans); }
5、Mapper.xml,放在指定的classpath:mapper/*Mapper.xml下
注意:Mapper.xml若放在依赖的包resources下,如common包,则路径要设置为 classpath*:mapper/*Mapper.xml
若mapper路径下还有子路径,则设置为classpath*:mapper/**/*Mapper.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.yang.spbo.mybatis.mapper.WeiboFansMapper">
<insert id="insertWeiboFans" parameterType="com.yang.spbo.mybatis.domain.WeiboFans">
insert into weibo_fans
(weibo_id,`name`,location,gender,profile,`desc`)
VALUE
(#{weiboId},#{name},#{location},#{gender},#{profile},#{desc})
</insert>
</mapper>
6、使用Mapper操作数据库
@Resource
private WeiboFansMapper weiboFansMapper;
@Test
void insertWeiboFansTest() {
WeiboFans weiboFans = new WeiboFans();
weiboFans.setId(745234093L);
weiboFans.setGender("m");
weiboFans.setName("杨豈Y");
weiboFans.setLocation("江苏 南京");
try {
weiboFansMapper.insertWeiboFans(weiboFans);
} catch (Exception e) {
e.printStackTrace();
}
}
补充
直接使用sqlSession:
@Component public class CityDao { private final SqlSession sqlSession; public CityDao(SqlSession sqlSession) { this.sqlSession = sqlSession; } public City selectCityById(long id) { return this.sqlSession.selectOne("selectCityById", id); } }
application.properties可用的配置:
Property | Description |
---|---|
config-location |
Location of MyBatis xml config file. |
check-config-location |
Indicates whether perform presence check of the MyBatis xml config file. |
mapper-locations |
Locations of Mapper xml config file. |
type-aliases-package |
Packages to search for type aliases. (Package delimiters are “,; \t\n ”) |
type-aliases-super-type |
The super class for filtering type alias. If this not specifies, the MyBatis deal as type alias all classes that searched from type-aliases-package . |
type-handlers-package |
Packages to search for type handlers. (Package delimiters are “,; \t\n ”) |
executor-type |
Executor type: SIMPLE , REUSE , BATCH |
default-scripting-language-driver |
The default scripting language driver class. This feature requires to use together with mybatis-spring 2.0.2+. |
configuration-properties |
Externalized properties for MyBatis configuration. Specified properties can be used as placeholder on MyBatis config file and Mapper file. For detail see the MyBatis reference page. |
lazy-initialization |
Whether enable lazy initialization of mapper bean. Set true to enable lazy initialization. This feature requires to use together with mybatis-spring 2.0.2+. |
mapper-default-scope |
Default scope for mapper bean that scanned by auto-configure. This feature requires to use together with mybatis-spring 2.0.6+. |
configuration.* |
Property keys for Configuration bean provided by MyBatis Core. About available nested properties see the MyBatis reference page. NOTE: This property cannot be used at the same time with the config-location . |
scripting-language-driver.thymeleaf.* |
Property keys for ThymeleafLanguageDriverConfig bean provided by MyBatis Thymeleaf. About available nested properties see the MyBatis Thymeleaf reference page. |
scripting-language-driver.freemarker.* |
Properties keys for FreeMarkerLanguageDriverConfig bean provided by MyBatis FreeMarker. About available nested properties see the MyBatis FreeMarker reference page. This feature requires to use together with mybatis-freemarker 1.2.0+. |
scripting-language-driver.velocity.* |
Properties keys for VelocityLanguageDriverConfig bean provided by MyBatis Velocity. About available nested properties see the MyBatis Velocity reference page. This feature requires to use together with mybatis-velocity 2.1.0+. |
或者不在application.properties中配置,而是使用自定的Java配置:
@Configuration public class MyBatisConfig { @Bean ConfigurationCustomizer mybatisConfigurationCustomizer() { return new ConfigurationCustomizer() { @Override public void customize(Configuration configuration) { // customize ... } }; } }
MyBatis-Spring-Boot-Starter 会自动搜索实现 ConfigurationCustomizer 接口的 bean,并调用自定义 MyBatis 配置的方法。
二、Spring-Mybatis
1、jar包依赖
<!--mysql-connect--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!--mybatis-spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> <scope>compile</scope> </dependency> <!--事务--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
2、MySQL连接信息配置 mysql.properties
jdbc.url=jdbc:mysql://127.0.0.1:3306/database_name?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=true jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.username=root jdbc.password=root
3、mybatis-config.xml Mybatis配置文件,可省略
4、数据源配置
注意:如果存在多个数据源的情况,需要配置多个DataSourceConfig,在每个DataSourceConfig上面basePackages扫描不同的Mapper接口,不同包下面的Mapper即可使用不同的数据源
import org.apache.commons.dbcp.BasicDataSource; import org.apache.ibatis.session.ExecutorType; 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.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; /** * @PropertySource 读取mysql.propertis中的配置保存到运行的环境变量Environment中 * @MapperScan * basePackage:用于扫描MyBatis Mapper接口的基本包。注意,只有具有至少一个方法的接口才会被注册 * sqlSessionTemplateRef:当有多个数据源时,用来指定在spring上下文中有多个sqlessiontemplate时使用哪个sqlessiontemplate */ @MapperScan(basePackages = "com.yang.spmy.springmybatis.mapper",sqlSessionTemplateRef = "sqlSessionTemplate") @Configuration @PropertySource("classpath:mysql.properties") public class DataSourceConfig { @Value("${jdbc.driver}") private String diverClassName; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(diverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setMaxActive(10); dataSource.setMaxIdle(2); dataSource.setMinIdle(1); dataSource.setMaxWait(6000); // 用来验证连接是否生效的sql语句 dataSource.setValidationQuery("SELECT 1"); // 从池中获取连接前进行验证 dataSource.setTestOnBorrow(true); // 向池中还回连接前进行验证 dataSource.setTestOnReturn(false); // 连接空闲时验证 dataSource.setTestWhileIdle(true); // 运行判断连接超时任务的时间间隔,单位为毫秒,默认为-1,即不执行任务 dataSource.setTimeBetweenEvictionRunsMillis(40000); // 连接的超时时间,默认为半小时 dataSource.setMinEvictableIdleTimeMillis(50000); return dataSource; } @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // mapper xml文件,有两种方式 ①:MyBatis的XML配置文件中的<mappers>中指定XML文件的类路径 ②:设置工厂bean的mapperLocations属性 sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/**/*Mapper.xml")); // 数据源 sqlSessionFactoryBean.setDataSource(dataSource()); // Resource config = new ClassPathResource("mybatis-config.xml"); // MyBatis XML配置文件路径 // sqlSessionFactoryBean.setConfigLocation(config); return sqlSessionFactoryBean.getObject(); } @Bean("sqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate() throws Exception { return new SqlSessionTemplate(sqlSessionFactory()); } @Bean("batchSqlSessionTemplate") public SqlSessionTemplate batchSqlSessionTemplate() throws Exception { return new SqlSessionTemplate(sqlSessionFactory(), ExecutorType.BATCH); } @Bean("dataSourceTransactionManager") public DataSourceTransactionManager transactionManager() { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); // Spring容器管理事务,指定数据源 dataSourceTransactionManager.setDataSource(dataSource()); return dataSourceTransactionManager; } }
配置说明:
sqlSession和事务与数据源关系:
5、定义Mapper接口,@Mapper注解可省略
@Mapper public interface TestMapper { Category selectById(Long id); }
6、Mapper.xml,放在指定的classpath:mapper/*Mapper.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.yang.spmy.springmybatis.mapper.TestMapper"> <sql id="column"> `id`, `parent`, `name`, `type`, `level`, `update_time`, `create_time` </sql> <select id="selectById" resultType="com.yang.spmy.springmybatis.model.Category"> select <include refid="column"/> from `category` where `id` = #{id} </select> </mapper>
7、使用Mapper操作数据库
@Autowired private TestMapper testMapper; @Test void categoryTest() { Category category = testMapper.selectById(15L); System.out.println(category); }
附录:
Spring-Mybatis官方文档:http://mybatis.org/spring/zh/index.html
SpringBoot-Mybatis官方文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
END.