Technology Sharing

Mybatis left join implementation method

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

When using MyBatis Plus for database operations, we sometimes need to get data from multiple tables. This article will introduce how to implement left join queries in MyBatis Plus. We will take two tables as examples, one is the department leader table (system_dept_leader), and the other is the user table (system_user), and demonstrates how to use a left join to obtain detailed information about the department head, including the user's nickname and work number.

Data table structure

Suppose we have the following two data tables:

Department Leaders Table (system_dept_leader)

Field Nametypedescribe
idLongPrimary Key
dept_idLongDepartment ID
user_idLongUser ID
is_primaryIntegerIs it main

 

user table (system_user)

Field Nametypedescribe
idLongPrimary Key
nicknameStringNick name
worker_codeStringJob number

Implementation steps

We will implement the left join query by following the steps below:

  1. Define the query result class
  2. Writing SQL Providers
  3. Define query methods in the Mapper interface

1. Define the query result class

First, we need to define a query result class to store query results. Here we define a DeptLeaderDORespVO Class, inherited from the base classDeptLeaderDOBaseVO, and contains the user's nickname and work number fields.

  1. @Data
  2. @EqualsAndHashCode(callSuper = true)
  3. @ToString(callSuper = true)
  4. public class DeptLeaderDORespVO extends DeptLeaderDOBaseVO {
  5. private Long id;
  6. @NotNull(message = "Department不能为空")
  7. private Long deptId;
  8. @NotNull(message = "User不能为空")
  9. private Long userId;
  10. @NotNull(message = "Is Primary不能为空")
  11. private Integer isPrimary;
  12. private String nickname;
  13. private String workerCode;
  14. }

2. Write a SQL provider

Next, we write a SQL provider class to dynamically generate SQL queries. SelectProvider Annotation to specify custom SQL.

  1. public class DeptLeaderSqlProvider {
  2. public String selectDeptLeaderWithUserDetails(Map<String, Object> params) {
  3. Long deptId = (Long) params.get("deptId");
  4. Long userId = (Long) params.get("userId");
  5. Integer isPrimary = (Integer) params.get("isPrimary");
  6. StringBuilder sql = new StringBuilder();
  7. sql.append("SELECT dl.*, su.nickname, su.worker_code AS workerCode ");
  8. sql.append("FROM system_dept_leader dl ");
  9. sql.append("LEFT JOIN system_user su ON dl.user_id = su.id ");
  10. sql.append("WHERE 1=1 ");
  11. if (deptId != null) {
  12. sql.append("AND dl.dept_id = #{deptId} ");
  13. }
  14. if (userId != null) {
  15. sql.append("AND dl.user_id = #{userId} ");
  16. }
  17. if (isPrimary != null) {
  18. sql.append("AND dl.is_primary = #{isPrimary} ");
  19. }
  20. sql.append("ORDER BY dl.id DESC");
  21. return sql.toString();
  22. }
  23. }

3. Define query methods in the Mapper interface

Finally, define the query method in the Mapper interface and use SelectProvider Annotation specifies the SQL provider.

  1. @Mapper
  2. public interface DeptLeaderMapper extends BaseMapperX<DeptLeaderDO> {
  3. @SelectProvider(type = DeptLeaderSqlProvider.class, method = "selectDeptLeaderWithUserDetails")
  4. List<DeptLeaderDORespVO> selectDeptLeaderWithUserDetails(@Param("deptId") Long deptId,
  5. @Param("userId") Long userId,
  6. @Param("isPrimary") Integer isPrimary);
  7. }

4. Calling service layer methods

The query method is called in the service layer and the results are returned to the front end or for further processing.

  1. @Service
  2. public class DeptLeaderService {
  3. @Autowired
  4. private DeptLeaderMapper deptLeaderMapper;
  5. public List<DeptLeaderDORespVO> getDeptLeaders(Long deptId, Long userId, Integer isPrimary) {
  6. return deptLeaderMapper.selectDeptLeaderWithUserDetails(deptId, userId, isPrimary);
  7. }
  8. }

Summarize

Through the above steps, we have implemented a method to query the detailed information of department leaders using left join in MyBatis Plus. This method can dynamically generate SQL queries based on the passed conditions to obtain the information of department leaders and their associated users. This method is very useful when data queries need to be performed across multiple tables, ensuring the flexibility and efficiency of data queries.

I hope this article can help you better understand and use MyBatis Plus for complex queries. If you have any questions or further requirements, please feel free to discuss and communicate.