spring boot使用总结(七)在spring boot中使用mybatis注解

mybatis3开始支持java注解,使用java注解可以替代xml配置文件,简化代码。下面来看一下怎么在spring boot中使用mybatis注解。

1 使用mybatis注解需要的配置。如下面的代码所示,使用@MapperScan来扫描注册mybatis数据库接口类,其中basePackages属性表明接口类所在的包,sqlSessionTemplateRef表明接口类使用的SqlSessionTemplate。如果项目需要配置两个数据库,@MapperScan也需要分别配置。

@Configuration
@MapperScan(basePackages="com.boot.test.mapper",sqlSessionTemplateRef="sqlSessionTemplate")
public class DatabaseConfig {

    @Bean
    @ConfigurationProperties(prefix = "test.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        return sessionFactory.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

2 mybatis注解介绍
mybatis3支持多个java注解,下面介绍几个基本的注解。
@Insert

 @Insert("insert into t_user(name,age,gender) values (#{name},#{age},#{gender})")
 public int addUser(User user) throws DataAccessException;

如上面的代码所示,使用@Insert注解可以在()中直接写sql语句,传参可以用#{}实现,其中name字段名直接对应User类中的name字段,肿么样,有没有很直观方便:)

@Select

@Select("select age,gender from t_user where name={name}")
public User queryUser(String name) throws DataAccessException;

@Select 注解所查询出的字段可以直接绑定到User类中对应的字段中,由于在类中可以import对应的类,免去了在xml中配置结果集的麻烦。

@SelectKey

 @SelectKey(statement = "select max(id) from t_id", before = true, resultType = long.class, keyProperty = "id")
 @Insert("insert into t_user(id,name,age,gender) values (#{id},#{name},#{age},#{gender})")
 public int addUser(User user) throws DataAccessException;

@SelectKey注解用于查询一下需要的前置字段,如上面的代码所示先查出id字段的值,然后插入到t_user表中,一般配合@Insert和@Update
注解使用。

版本说明:spring boot: 1.4.0.RELEASE   mybatis: 3.2.3  mybatis-spring: 1.2.2

参考文档:http://www.mybatis.org/mybatis-3/java-api.html 参见Mapper Annotations 部分

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,081评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,486评论 19 139
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 11,158评论 0 4
  • 昏暗的灯光,稀疏的路人,我走在返乡的路上。不知走了多久,我才敲开了奶奶家的大门。“奶奶,我来看您了!”我喊...
    樱花雨未迟阅读 1,865评论 2 4
  • 相册里多了些废墟的照片,小时候呆了十几年的片区要拆了,混童年的地方已成一片狼藉。 几次回去总会不自觉拍些照片,都是...
    哆咪demi阅读 1,657评论 0 0