SoFunction
Updated on 2025-04-11

Use mybatisPlus queryWrapper for left join and in-join

MybatisPlus queryWrapper does left join and in-link

Generate Java code using mybatisplus querywapper in service layer

SELECT
bs_user.id,
bs_user.mobile,
bs_user.username,
bs_user.password,
bs_user.enable_state,
ss_user_social_security.user_id,
ss_user_social_security.enterprises_pay_social_security_this_month,
ss_user_social_security.enterprises_pay_the_provident_fund_this_month,
ss_user_social_security.participating_in_the_city_id,
ss_user_social_security.social_security_type,
ss_user_social_security.household_registration_type,
ss_user_social_security.social_security_base,
ss_user_social_security.industrial_injury_ratio
FROM
bs_user
LEFT JOIN
ss_user_social_security
ON
bs_user.id = ss_user_social_security.user_id
INNER JOIN
ss_company_settings
ON
bs_user.company_id = ss_company_settings.company_id
WHERE
ss_company_settings.company_id = 1 The table structure andvoObject

You can refer to the following code to execute this query

  • Using Mybatis-Plus' QueryWrapper simplifies SQL construction and avoids the problem of misspelling keywords
  • Suppose you already have the corresponding VO class, which contains all the properties in the above query result and their Getter/Setter methods

You can refer to the following code:

// Create a QueryWrapper objectQueryWrapper<UserVO> queryWrapper = new QueryWrapper<>();

// Set the field to query("bs_user.id", "bs_user.mobile", "bs_user.username", "bs_user.password", 
    "bs_user.enable_state", "ss_user_social_security.user_id", 
    "ss_user_social_security.enterprises_pay_social_security_this_month", 
    "ss_user_social_security.enterprises_pay_the_provident_fund_this_month", 
    "ss_user_social_security.participating_in_the_city_id", 
    "ss_user_social_security.social_security_type", "ss_user_social_security.household_registration_type", 
    "ss_user_social_security.social_security_base", "ss_user_social_security.industrial_injury_ratio");

// Add association table("ss_user_social_security", "bs_user.id = ss_user_social_security.user_id");
("ss_company_settings", "bs_user.company_id = ss_company_settings.company_id");

// Add query conditions("ss_company_settings.company_id", 1);

// Call the service layer method to execute queryList<UserVO> userList = (queryWrapper);
  • In this code, we use the QueryWrapper object to build SQL statements.
  • By calling methods such as select and join, we can set the fields to query and add the association table.
  • Finally, use eq and other methods to set the query conditions.
  • Finally, the list method is called to execute the query and the result is stored in a List object and returned.
  • Note that the VO class and service call methods in the above code should be replaced according to specific needs.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.