接上一节基于注解整合mybatis。
新建如下目录及文件:
首先在application.yml中加上mybatis配置文件的位置以及mapper.xml存在的位置。
mybatis: config-location: classpath:mybatis/mybatis-config.xml 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>
然后就可以进行测试了。
EmployeeMapper.java
package com.gong.springbootjdbc.mapper; import com.gong.springbootjdbc.bean.Employee; //@Mapper或者@MapperScan将接口扫描装配到容器中 public interface EmployeeMapper { public Employee getEmpById(Integer id); public void insertEmp(Employee employee); }
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.gong.springbootjdbc.mapper.EmployeeMapper"> <!-- public Employee getEmpById(Integer id); public void insertEmp(Employee employee);--> <select id="getEmpById" resultType="com.gong.springbootjdbc.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>
EmpController.java
package com.gong.springbootjdbc.controller;
import com.gong.springbootjdbc.bean.Employee;
import com.gong.springbootjdbc.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmpController {
@Autowired
EmployeeMapper employeeMapper;
@RequestMapping("/emp/{id}")
public Employee getEmpById(@PathVariable("id") Integer id){
return employeeMapper.getEmpById(id);
}
@RequestMapping("/emp")
public Employee insertEmp(Employee employee){
employeeMapper.insertEmp(employee);
return employee;
}
}
原文:https://www.cnblogs.com/xiximayou/p/12286618.html