码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot整合MyBatis(注解版)

时间:2019-02-01 19:48:20      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:整合   nbsp   ann   values   bsp   mod   详情   not   case   

详情可以参考Mybatis官方文档  http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

(1)、引入Mybatis针对SpringBoot制作的Starter依赖

1         <dependency>
2             <groupId>org.mybatis.spring.boot</groupId>
3             <artifactId>mybatis-spring-boot-starter</artifactId>
4             <version>2.0.0</version>
5         </dependency>

 

(2)、配置Mybatis设置

 1 package cn.coreqi.config;
 2 
 3 import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.Configuration;
 6 
 7 @Configuration
 8 public class MybatisConfig {
 9     @Bean
10     public ConfigurationCustomizer configurationCustomizer(){
11         return new ConfigurationCustomizer() {
12             @Override
13             public void customize(org.apache.ibatis.session.Configuration configuration) {
14                 configuration.setMapUnderscoreToCamelCase(true);    //开启驼峰命名
15             }
16         };
17     }
18 }

(3)、编写Mapper接口

 1 package cn.coreqi.mapper;
 2 
 3 import cn.coreqi.entities.User;
 4 import org.apache.ibatis.annotations.*;
 5 
 6 //@Mapper   告诉SpringBoot这是一个操作数据库的mapper
 7 @Mapper
 8 public interface UserMapper {
 9     @Select("select * from users where Id = #{id}")
10     public User getUserById(Integer id);
11 
12     @Insert("insert into users(UserName,PassWord,Enabled) values(#{UserName},#{PassWord},#{Enabled})")
13     @Options(useGeneratedKeys = true,keyProperty = "Id")    //使用自增主键,并指定主键的列名称
14     public int addUser(User user);
15 
16     @Update("update users set UserName = #{UserName},PassWord = #{PassWord},Enabled = #{Enabled} where Id = #{Id}")
17     public int modifyUser(User user);
18 
19     @Delete("delete from users where Id = #{id}")
20     public int delUserById(Integer id);
21 
22 }

(4)、扫描所有的Mapper接口

 1 package cn.coreqi;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 
 7 @SpringBootApplication
 8 @MapperScan(value = "cn.coreqi.mapper")     //扫描指定路径下所有的Mapper接口
 9 public class SpringbootjdbcApplication {
10 
11     public static void main(String[] args) {
12         SpringApplication.run(SpringbootjdbcApplication.class, args);
13     }
14 
15 }

 

SpringBoot整合MyBatis(注解版)

标签:整合   nbsp   ann   values   bsp   mod   详情   not   case   

原文地址:https://www.cnblogs.com/fanqisoft/p/10346743.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!