1.创建项目时勾选以下模块

2.注解版

注解版的Mapper

package com.moti.mapper;

import com.moti.bean.Department;
import org.apache.ibatis.annotations.*;

//指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {
    @Select("select * from department where id = #{id}")
    public Department getDeptById(int id);
    @Delete("delete from department where id = #{id}")
    public int deleteDeptById(int id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values (#{departmentName})")
    public int addDept(Department department);
    @Update("update department set departmentName = #{departmentName} where id = #{id}")
    public int updateDeptById(Department department);
}

注解版的全局配置文件

package com.moti.config;

import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

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

            @Override
            public void customize(Configuration configuration) {
                //开启驼峰命名
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

3.配置文件版

全局配置文件

<?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>
    <!--关于MyBatis的一些常用配置-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING" />
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

</configuration>

Mapper映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.moti.mapper.EmployeeMapper">
    <select id="getEmpById" resultType="com.moti.bean.Employee">
        select * from employee where id = #{id}
    </select>
    <insert id="addEmp">
        insert into employee(lastName,email,gender,d_id) values (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

这里需要在SpringBoot的配置文件中配置MyBatis配置文件的位置,如下

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
最后修改日期:2020-07-12

作者

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。