MyBatis queries the entity class and queries other classes referenced by the entity class

Problem Description:

There are two tables in the database-employee table and department table, corresponding to the two entity classes Employee and Department. Since each employee must have a department, the Department needs to be referenced in Employee.

At first I thought that MyBatis requires the attributes of the entity class to correspond to the fields of the database table. Employee uses the id of the Department, but this will cause the front-end display to only display the department id (if the back-end uses id to check the department name) Can also be achieved, but more troublesome).

Later, I switched to using the Department object directly in Employee, but I don't know how to write SQL in EmployeeMapper.xml, and I found the answer after various searches.

Solution

First, query the required information in the department table and employee table through the query of the join table, and then use the alias to change the field name found in the department table to the attribute name of the Department class.

 

Entity class

Employee

package com.zcy.pojo;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@NoArgsConstructor
public class Employee {
    
    
    private int id;
    private String name;
    private String email;
    private int gender;//女0,男1
    private Department department;
    private Date birthday;
}

 

Department

package com.zcy.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
    
    
    private int id;//部门ID
    private String name;//部门名称
}

 

SQL in MyBatis

<select id="queryAllEmployee" resultType="employee">
    select
    a.id, a.name, a.email, a.gender,
    b.id "department.id",
    b.name "department.name",
    birthday
    from employee a
    inner join department b
    where a.department_id = b.id;
</select>

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_39763246/article/details/114456179