spring-boot 2.1.3整合Mybatis

一、注解版

1.添加依赖

<dependency>
   <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>2.0.0version>
dependency>

2.配置数据源
3.写mapper接口

package com.edward.springbootmybaties.mapper;

import com.edward.springbootmybaties.bean.User;
import org.apache.ibatis.annotations.*;

@Mapper
public interface UserMapper {

    @Select("select * from user where id=#{id}")
    public User getUserById(Integer id);

    @Delete("delete * from user where id=#{id}")
    public int deleteUserById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into user(username,password) values(#{username},#{password})")
    public int insertUser(User user);

    @Update("update user set username=#{username},password=#{password}")
    public int updateUser(User user);


}

4.使用


	//UserMapper使用的是@Mapper注解,IDEA会提示错误UserMapper找不到,但不影响运行
    @Autowired
    UserMapper userMapper;

    @ResponseBody
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id){
        User user = userMapper.getUserById(id);
        return user;
    }

    @ResponseBody
    @GetMapping("/user")
    public User insertUser(User user){
        int i = userMapper.insertUser(user);
        return user;
    }

5.自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){
            @Override
            public void customize(Configuration configuration) {
            	//开启驼峰命名法
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

6.使用MapperScan批量扫描所有的Mapper接口,这样不用在每个Mapper文件上加@Mapper注解

@MapperScan(basePackages = "com.edward.sprignbootmybaties.mapper")
@SpringBootApplication
public class SpringBootMybatiesApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootMybatiesApplication.class, args);
    }

}

二、 配置文件版

创建mybatis-config.xml和xxxMapper.xml文件
spring-boot 2.1.3整合Mybatis_第1张图片
mybatis-config.xml文件



<configuration>

    //开启驼峰命名
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>
configuration>

xxxMapper.xml文件



<mapper namespace="com.atguigu.springboot.mapper.EmployeeMapper">
    
    <select id="getEmpById" resultType="com.atguigu.springboot.bean.Employee">
        SELECT * FROM employee WHERE id=#{id}
    select>

    <insert id="insertEmp">
        INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
    insert>
mapper>

在application.yml文件中

mybatis:
  config‐location: classpath:mybatis/mybatis‐config.xml 指定全局配置文件的位置
  mapper‐locations: classpath:mybatis/mapper/*.xml  指定sql映射文件的位置

你可能感兴趣的:(Sprign-Boot)