Skip to main content

10.多表联查示例

在多表联查方面,MyBatis-Plus提供了一些方便的方式来执行复杂的SQL查询,并将结果映射到Java对象中。

环境搭建

假设我们有两个实体类 UserRole,对应数据库中的 user表和 role表,其中 user表和 role表通过外键 role_id建立了关联关系。

实体类(Entity Classes)

public class User {
private Long id;
private String username;
private String email;
private Long roleId;

// Getters and setters
}

public class Role {
private Long id;
private String roleName;

// Getters and setters
}

Mapper接口(Mapper Interfaces)

@Mapper
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT u.*, r.role_name FROM user u INNER JOIN role r ON u.role_id = r.id WHERE u.id = #{id}")
UserWithRole selectUserWithRoleById(Long id);
}

服务类(Service Class)

@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;

@Override
public UserWithRole getUserWithRoleById(Long id) {
return userMapper.selectUserWithRoleById(id);
}
}

控制器类(Controller Class)

@RestController
public class UserController {
@Autowired
private UserService userService;

@GetMapping("/users/{id}")
public ResponseEntity<UserWithRole> getUserWithRoleById(@PathVariable Long id) {
UserWithRole userWithRole = userService.getUserWithRoleById(id);
return ResponseEntity.ok(userWithRole);
}
}
  • 通过 @Select注解定义了一个自定义的SQL查询方法 selectUserWithRoleById,该方法执行了一个内连接查询,将 user表和 role表联合起来,根据用户ID查询对应的用户信息和角色信息,并将结果映射到 UserWithRole对象中。
  • 然后,我们在服务类中调用这个方法,并将查询结果返回给控制器。
  • 最后,控制器将查询结果封装成 ResponseEntity并返回给客户端。

总结

实际项目中可能会涉及更复杂的多表查询,但基本思路是相似的:

  1. 定义SQL查询语句
  2. 将查询结果映射到Java对象中
  3. 然后在服务类中调用查询方法
  4. 最终将结果返回给控制器。