Spring Boot注解方式集成Mybatis

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot注解方式集成Mybatis相关的知识,希望对你有一定的参考价值。

一、无配置文件注解版
1.pom文件必要jar包的引入
1 <dependency>
2 <groupId>mysql</groupId>
3 <artifactId>mysql-connector-java</artifactId>
4 </dependency>
5 <dependency>
6 <groupId>org.mybatis.spring.boot</groupId>
7 <artifactId>mybatis-spring-boot-starter</artifactId>
8 <version>1.1.1</version>
9 </dependency>

 

2.application.properties添加相关配置
  SpringBoot会自动加载application.properties配置文件,会读取spring.datasource.*相关的配置,数据源会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中
  会扫描的model实体类路径
1 mybatis.type-aliases-package=com.neo.entity spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/test1?
2 useUnicode=true&characterEncoding=utf-8
3 spring.datasource.username = root
4 spring.datasource.password = root

 

3.建立启动类
@SpringBootApplication @MapperScan("com.neo.mapper") 
public class Application { 
    public static void main(String[] args) {         
        SpringApplication.run(Application.class, args); 
    } 
}

   或者在Mapper雷尚添加注解@Mapper

4.mapper文件配置
 
 1 public interface UserMapper { 
 2 @Select("SELECT * FROM users") @Results({ @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class), @Result(property = "nickName", column = "nick_name") }) List<UserEntity> getAll();
 3 @Select("SELECT * FROM users WHERE id = #{id}") 
 4 @Results({ @Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class), 
 5 @Result(property = "nickName", column = "nick_name") }) 
 6 UserEntity getOne(Long id); @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})") void insert(UserEntity user); 
 7 @Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}") 
 8 void update(UserEntity user); 
 9 @Delete("DELETE FROM users WHERE id =#{id}") 
10 void delete(Long id); }

 

5测试类
技术分享

 

 
 

以上是关于Spring Boot注解方式集成Mybatis的主要内容,如果未能解决你的问题,请参考以下文章

264.Spring Boot MyBatis集成MyBatis-Plus

spring boot集成mybatis+事务控制

spring boot 学习之路3( 集成mybatis )

Spring Boot集成Mybatis完整实例

聊聊Mybatis集成Spring 注解方式

spring boot集成了druid后,同样的mybatis模糊查询语句出错Caused by: com.alibaba.druid.sql.parser.ParserException: sy(代