SpringBoot整合MyBatis(注解版)
详情可以参考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 }