mybatisplus左连接查询
时间: 2023-08-30 14:05:01 浏览: 157
在MyBatis Plus中进行左连接查询,你可以使用Wrapper对象来构建查询条件。以下是一个示例代码:
```java
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.User;
import com.example.demo.entity.UserDetail;
import com.example.demo.mapper.UserMapper;
import com.example.demo.mapper.UserDetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private UserDetailMapper userDetailMapper;
public IPage<User> getUsersWithDetails() {
// 构建分页对象
IPage<User> page = new Page<>(1, 10);
// 构建查询条件
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("status", 1);
// 执行查询
IPage<User> result = userMapper.selectPage(page, queryWrapper);
// 返回查询结果
return result;
}
public User getUserWithDetail(Long userId) {
// 构建查询条件
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", userId);
// 执行查询
User user = userMapper.selectOne(queryWrapper);
if (user != null) {
// 构建查询条件
QueryWrapper<UserDetail> detailQueryWrapper = new QueryWrapper<>();
detailQueryWrapper.eq("user_id", user.getId());
// 执行左连接查询
UserDetail userDetail = userDetailMapper.selectOne(detailQueryWrapper);
// 设置关联对象
user.setUserDetail(userDetail)
阅读全文