SpringBoot2.0(一) mybatis

使用mybatis

springboot使用mybatis主要依赖 mybatis-spring-boot-starter 来实现。其提供了2中解决方案,一种是使用注解;另一种是简化后的传统的xml方式。

compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2')

application.properties相关配置

mybatis.configuration.map-underscore-to-camel-case=true
mybatis.type-aliases-package=com.xxxxxx.domain
mybatis.mapper-locations=classpath*:sql/*/*.xml

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/hr?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=

在启动类上添加对mapper包的扫描@MapperScan

@SpringBootApplication
@MapperScan(
		basePackages = "com.xxxxxxx.dao"
)
public class XXApplication {

	public static void main(String[] args) {
		SpringApplication.run(XXApplication.class, args);
	}
}

  

sql脚本的处理方式有如下2种:

注解

public interface UserMapper {
	
	@Select("SELECT * FROM users")
	@Results({
		@Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
		@Result(property = "nickName", column = "nick_name")
	})
	List<UserEntity> getAll();
	
	@Select("SELECT * FROM users WHERE id = #{id}")
	@Results({
		@Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
		@Result(property = "nickName", column = "nick_name")
	})
	UserEntity getOne(Long id);

	@Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
	void insert(UserEntity user);

	@Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")
	void update(UserEntity user);

	@Delete("DELETE FROM users WHERE id =#{id}")
	void delete(Long id);

}

  

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.xxxxxx.Dao">

    <select id="queryXxxx" parameterType="Query" resultType="Result">
        select * from xxx
        <where>
            <if test="xxx != null">
                and xxx = #{xxx}
            </if>
        </where>
    </select>
</mapper>

 

多数据源

上述配置在单数据源下可以正常使用。在多数据源下,配置有些变化。

在使用springboot打包构建可执行jar时,mybatis 默认的vfs读取xml资源会存在问题,其不支持从多层级Jar文件中读取相关配置信息。

故在声明sqlSessionFactory时,指定vfs为springboot提供的VFS实现。

如下code:

@Configuration
@MapperScan(basePackages = "com.xxx.daohistory", sqlSessionTemplateRef = "sqlSessionTemplate")
public class HistoryConfig {

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setVfs(SpringBootVFS.class);
        factoryBean.setTypeAliasesPackage("com.xxxxx.domain");

        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:sqlhistory/*.xml"));

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);

        factoryBean.setConfiguration(configuration);

        return factoryBean.getObject();
    }

    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate sbtSqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

多个数据源的时候,上述配置配置多份,相应的name做下处理即可。

猜你喜欢

转载自www.cnblogs.com/asfeixue/p/9112733.html