非常简单的一对多的关系-一个人对许多宠物。
@Entity
class Human{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy="human", cascade={CascadeType.ALL})
private List<Pet> pets;
// other fields
}
@Entity
class Pet{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="human_id")
private Human human;
// others fields
}这导致两个表创建了HUMAN(id)和PET(id,human_id)。
编辑-1:我正在使用Spring
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>编辑-2:下面是我如何发布数据的最新内容。我正在向人类发帖:
{
// human data
"pets": [
"http://localhost/pets/1",
"http://localhost/pets/2"
]
}Problem:PET表中的human_id列为null。所有其他字段都已找到,但关系尚未建立。
我遗漏了什么?
发布于 2017-01-14 16:50:35
通过移除mappedBy并将@JoinColumn放在@OneToMany旁边,我得以保持这种关系。
,这有什么问题吗?性能问题?
@Entity
class Human{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JoinColumn(name="human_id")
@OneToMany(cascade={CascadeType.ALL})
private List<Pet> pets;
// other fields
}
@Entity
class Pet{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(cascade=CascadeType.ALL)
private Human human;
// others fields
}发布于 2017-01-14 04:55:18
首先,在@ManyToOne列中使用CascadeType.ALL是危险的。当宠物被删除时,它可以删除一个人。
和,
将每个对象关联后保存haman
Human human = new Human();
Pet pet1 = new Pet();
pet1.setHuman(human);
Pet pet2 = new Pet();
pet2.setHuman(human);
List<Pet> pets = new ArrayList<Pet>();
pets.add(pet1);
pets.add(pet2);
human.setPets(pets);然后保存human
https://stackoverflow.com/questions/41646880
复制相似问题