欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 整合mybatis

程序员文章站 2022-04-23 15:45:14
...

一:注解模式整合

spring boot默认以注解版与mybatis底层整合,MybatisAutoConfiguration中MybatisProperties种属性字段允许用户自定义配置。SqlSessionFactory对象也在配置类中自动注入;我们只需要编写dao层即可。

@Mapper
public interface DepartmentMapper {

    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(department_name) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set department_name=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

为了支持驼峰法命名,需要手动写一个配置类,重写ConfigurationCustomizer类中方法customize;

 

public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

 

上面的@Mapper注解必须要有,否则需要在启动类中添加@MapperScan(value =“com.*”)

二:xml配置模式

首先application.yml中添加xml配置文件目录

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

添加相应mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

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

这样添加完成后,dao层只需要写相应的接口,不需要在写相应的注解sql;

数据源配置参考前文介绍:https://blog.csdn.net/Java_Jsp_Ssh/article/details/83119798