zoukankan      html  css  js  c++  java
  • 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做下处理即可。

  • 相关阅读:
    十分钟-Nginx 入门到上线
    83.面向忙碌开发者的 Android 知识点收录 (转)
    技术人,为什么需要构建知识图谱 (转载)
    C# 4.0四大新特性代码示例与解读
    .NET 项目代码风格要求
    .NET 推荐博客
    C# 五、谈扩展方法的理解
    ASP.NET 一步步开发自己的博客 .NET版(11、Web.config文件的读取和修改)
    ASP.NET 你必须知道的EF知识和经验
    Linq表达式、Lambda表达式你更喜欢哪个?
  • 原文地址:https://www.cnblogs.com/asfeixue/p/9112733.html
Copyright © 2011-2022 走看看