整合MyBatis

Posted 小亮的BLOG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了整合MyBatis相关的知识,希望对你有一定的参考价值。

配置数据源相关属性(见前一章节 DataSource配置

引入依赖

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
</dependency>

application.properties

mybatis.mapper-locations=classpath:public/mybatis/mapper/*.xml 
mybatis.config-location=classpath:public/mybatis/mybatis-config.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>

EmployeeMapper.xml

<?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.atguigu.springBoot01.mapper.EmployeeMapper">
    <!-- public Employee getEmpById(Integer id); public void insertEmp(Employee 
        employee); -->

    <resultMap type="com.atguigu.springBoot01.entity.Employee" id="empMap">
        <id column="id" property="id" />
        <result column="lastName" property="lastName" />
        <result column="email" property="email" />
        <result column="gender" property="gender" />
        <result column="department_id" property="department.id" />
    </resultMap>

    <select id="getEmpById" resultMap="empMap">
        SELECT * FROM t_employee WHERE id=#{id}
    </select>

    <insert id="insertEmp" parameterType="com.atguigu.springBoot01.entity.Employee">
        INSERT INTO t_employee(last_name,email,gender,department_id) VALUES
        (#{lastName},#{email},#{gender},#{department.id})
    </insert>
</mapper>

EmployeeMapper接口

package com.atguigu.springBoot01.mapper;

import com.atguigu.springBoot01.entity.Employee;

public interface EmployeeMapper {
    
    public Employee getEmpById(Integer id);
    
    public void insertEmp(Employee emp);

}

使用MapperScan批量扫描所有的Mapper接口

@SpringBootApplication
@MapperScan(value = "com.atguigu.springBoot01.mapper")
public class Application {
public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

 

以上是关于整合MyBatis的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis学习--spring和Mybatis整合

springboot整合mybatis,redis,代码

Mybatis--02

SpringBoot整合Mybatis之Annotation

请教mybatis+spring+atomikos的整合问题

springboot整合mybatis,redis,代码