Spring Boot 使用XML文件配置 MyBatis

1,创建一个接口,@Mapper或者@MapperScan将接口扫描装配到容器中

JavaBean:

public class Employee {

    private Integer id;
    private String lastName;
    private Integer gender;
    private String email;
    private Integer dId;

    public void setId(Integer id) {
        this.id = id;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setdId(Integer dId) {
        this.dId = dId;
    }

    public Integer getId() {
        return id;
    }

    public String getLastName() {
        return lastName;
    }

    public Integer getGender() {
        return gender;
    }

    public String getEmail() {
        return email;
    }

    public Integer getdId() {
        return dId;
    }
}
public interface EmployeeMapper {

    public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);
}

在项目启动类上加上:

@MapperScan(value = "com.mydata.springboot.mapper")

Spring Boot 使用XML文件配置 MyBatis_第1张图片

2,创建一个XML的全局配置文件




    
    
        
    

3,创建一个XML的SQL映射文件





   

    

    
        INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
    

4,要让创建的XML文件生效,可以在application.yml配置文件中配置:

mybatis:
    # 指定全局配置文件位置
    config-location: classpath:mybatis/mybatis-config.xml
    # 指定sql映射文件位置
    mapper-locations: classpath:mybatis/mapper/*.xml

5,创建一个测试用的Controller

@RestController
public class DeptController {

    @Autowired
    EmployeeMapper employeeMapper;


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

}

6,在数据库里加入测试的数据

7,启动项目输入url访问:localhost:8080/emp/1

Spring Boot 使用XML文件配置 MyBatis_第2张图片

显示数据,这样就配置成功了!

 

 

 

 

你可能感兴趣的:(Spring-Boot)