毕设的学习(22)springboot使用mybatis注解进行一对多和多对多查询/

https://blog.swing1993.cn/springboot%e4%bd%bf%e7%94%a8mybatis%e6%b3%a8%e8%a7%a3%e8%bf%9b%e8%a1%8c%e4%b8%80%e5%af%b9%e5%a4%9a%e5%92%8c%e5%a4%9a%e5%af%b9%e5%a4%9a%e6%9f%a5%e8%af%a2/

 

 

一对一

每个人都有一个身份证号,且唯一。即一对一。

 

 

一对多

一个班级可以有多个学生,即一对多。

一个人可以拥有多辆车,也是一对多。

 

一对多

public class Car {
private Long id;
private String color;
private String name;
//用户id
private Long userId;
}

public class User {
private Long id;
//地址信息,和用户是一对一的关系
private Address address;
//地址id
private Long addressId;
//用户拥有的车,和用户是一对多的关系
private List<Car> cars;
}

举例:获取用户拥有的所有车car

 

一、在User(一对多中“一”的部分)写一个用户拥有的车的属性。

 

二、定义一个根据用户id查询车的查询方法

 

public interface CarRepository {

/** * 根据用户id查询所有的车 */

@Select("SELECT * FROM `car` WHERE user_id = #{userId}")

List<Car> findCarByUserId(Long userId);

}

 

三、再定义一个根据用户id查询用户信息的方法

public interface UserRepository {

@Select("SELECT * FROM `user` where id = #{id}")

User findUserWithAddress(Long id);

}

这个时候我们查询出来的user对象中的List属性是空的,和car的查询方法并没有任何关联。


那么我们要把user中的用户id传递给CarRepository的查询车的方法,


然后把查询出的集合对象List赋值给user的cars属性,那么我们怎么做呢?

 

四、public interface UserRepository {

/** * 查询带有车信息的用户===============演示一对多(关于多对多其实就是两个一对多组成) */

public interface UserRepository {
/**
* 查询带有车信息的用户===============演示一对多(关于多对多其实就是两个一对多组成)
*/
@Select("SELECT * FROM `user` WHERE id = #{id}")
@Results({
@Result(property = "cars", column = "id",
many = @Many(select = "com.kingboy.repository.car.CarRepository.findCarByUserId"))
})
User getUserWithCar(Long id);
}

要使用@Resutl注解对返回的结果进行配置
property = “cars”, 表示要将返回的查询结果赋值给user的cars属性
column = “id” 是指将user表中的用户主键id作为com.kingboy.repository.address.CarRepository.findCarByUserId的查询参数
many 表示这是一个一对多的查询
@Many(select = “方法全路径) 表示我们调用的方法, 方法参数userId就是上面column指定的列值







https://blog.csdn.net/dwenxue/article/details/82384890
mybatis 中间表 多对多 注解实现



欢迎大家关注我的微信公众号,获取你不知道的宝藏。




posted @ 2019-12-14 23:20  代码改变我的世界  阅读(497)  评论(0编辑  收藏  举报