使用mybatis实现对所有用户的收藏进行查询
实体类:用户表、收藏表
@Data:lombok的注解,使用后可以不写get,set方法
@TableName:mybatis-plus中的注解,与数据库库名对应,当数据库名与实体类名不一致或不符合驼峰命名时,需要在此注解指定表名
@TableField:与@TableName作用一致
@TableId(type = IdType.AUTO):id自增,不使用注解时,插入后由数据库进行自增,使用注解插入的id就是自增后的id
@TableField(exist = false):告诉它数据库中没有这个字段,这里的collects就是用来存放每个用户的收藏
@Data
@TableName("user_info")
public class User {
@TableField("user_id")
@TableId(type = IdType.AUTO)
private Integer userid;
private String username;
private String password;
private String phone;
private String icon;
//用户的所有收藏
@TableField(exist = false)
private List<Collect> collects;
}
@Data
public class Collect {
@TableField("collect_id")
private Integer collectId;
@TableField("user_id")
private Integer userId;
@TableField("post_id")
private Integer postId;
private Integer isCollect;
}
Mapper:UserMapper、CollectMapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
//根据用户id查询用户信息
@Select("select * from user_info where user_id = #{id}")
User getUserById(int id);
//查询用户所有收藏
@Select("select * from user_info")
@Results({
//column:数据库中的列名
//property:实体类中的字段名
@Result(column = "user_id",property = "userid"),
@Result(column = "username",property = "username"),
@Result(column = "password",property = "password"),
@Result(column = "phone",property = "phone"),
@Result(column = "icon",property = "icon"),
//告诉 MyBatis 该属性是一个多对多关联,并且通过 com.wzkj.helloworld.mapper.CollectMapper.collects 方法来加载关联数据
@Result(column = "user_id",property = "collects",javaType = List.class,
many = @Many(select = "com.wzkj.helloworld.mapper.CollectMapper.collects")
)
})
List<User> queryAllUsersAndCollect();
}
@Mapper
public interface CollectMapper extends BaseMapper<Collect> {
@Select("select * from collect where user_id = #{id}")
List<Collect> collects(int id);
}
Controller:UserController
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/users")
public List<User> queryUsers(){
return userMapper.queryAllUsersAndCollect();
}
}
最终结果