[英]Hibernate one to many: Should the entity contain the foreign key or the whole object
我正在尝试学习休眠API。 我在与人际关系以及如何使用关系方面遇到困难。
考虑以下示例。 我们有两个表,所有者和汽车。 我们假设一辆汽车只能由一个人拥有,因此汽车与车主有多对一的关系。
现在,常规的SQL数据库将如下所示。
|------------| |------------|
| Owner | 1 ------------------- N | Car |
|------------| |------------|
| id | | id |
| name | | model |
|------------| | car_id |
|------------|
现在,当我尝试使用注释编写实体时,最困难的部分就来了。
特别是Car实体。
我的问题是两个:
1,汽车类实体应该有一个长为carId的字段还是应该是所有者所有者字段?
2.我还应该在两个实体中都包括一对多和多对一关系,或者只需要一个就可以了。
先感谢您。
您应该具有双向关系,例如:
/*Many to one relationship with owner in class Car*/
public class Car {
@Id
private int id;
@ManyToOne
private Owner owner;
}
/*One to many relationship with car in class Owner*/
public class Owner {
@Id
private int id;
@OneToMany(mappedBy="owner")
private List<Car> cars;
}
因此,您应该使用“所有者”作为类型,如果要访问所有者的汽车和汽车所有者,则必须在两个类中都设置关系。
public class Car {
@Id private int id;
@ManyToOne private Owner owner;
private String model;
/** getters and setters */
}
public class Owner {
@Id private int id;
private String name;
@OneToMany private List<Car> cars;
/** getters and setters */
}
在提供的关系中,主实体是所有者。 以现实生活为例,所有者可以拥有多辆汽车。 在这种情况下,每辆车都应引用所有者(owner_id),也可以使用关系表。 您可以指定单向映射或双向映射。
单向示例:
public class Owner {
@OneToMany
private List<Car> cars;
}
双向示例:
public class Owner {
@OneToMany(mappedBy = "owner")
private List<Car> cars;
}
public class Car {
@ManyToOne
private Owner owner;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.