1. 程式人生 > >SpringBoot和Mybatis整合二(基於配置檔案)

SpringBoot和Mybatis整合二(基於配置檔案)

專案結構:

EmployeeMapper:

package com.lucifer.springboot.mapper;

import com.lucifer.springboot.bean.Employee;

public interface EmployeeMapper {
    public Employee getEmployee(Integer id);

    public void insertEmp(Employee employee);
}

EmployeeMapper.xml:    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.lucifer.springboot.mapper.EmployeeMapper">
    <select id="getEmployee" resultType="com.lucifer.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>

mybatis-config.xml: mybatis配置檔案,mapUnderscoreToCamelCase設定為true,就可以開啟駝峰命名規則。

<?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>

application.yml: 增加兩行配置 

EmployeeController:

package com.lucifer.springboot.controller;

import com.lucifer.springboot.bean.Employee;
import com.lucifer.springboot.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: Lucifer
 * @create: 2018-09-20 15:00
 * @description:
 **/
@RestController
public class EmployeeController {

    @Autowired
    EmployeeMapper employeeMapper;

    @GetMapping("/emp/{id}")
    public Employee getemployee(@PathVariable("id") Integer id){
        return employeeMapper.getEmployee(id);
    }

}

瀏覽器輸入路徑:

ps:如果did對應的value是null的話,看資料庫中表中該欄位資料是否為空,再看是否開啟了駝峰命名規則。