整合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); } }

 

posted @ 2019-02-20 21:03  小亮的BLOG  阅读(123)  评论(0编辑  收藏  举报