[英]Hibernate: Is it possible to persist only a child which will cause persisting a parent as well
Let's say I have a parent table A and a child table B, they have a foreign key linking A.id and B.id, the problem is this parent table and the FK have been created recently and there are too many places which persisting a child table, so I'm waiting for a simple way to persist the parent table and link it to the child table. 假设我有一个父表A和一个子表B,它们有一个链接A.id和B.id的外键,问题是此父表和FK是最近创建的,并且存在太多持久化a的位置子表,所以我在等待一种简单的方法来保留父表并将其链接到子表。 Is it possible to handle this task by using Hibernate instruments?
是否可以通过使用Hibernate工具来处理此任务? I was trying to use cascades but no success, looks they only work if we persist a parent entity.
我试图使用级联,但没有成功,看起来它们仅在我们保留父实体时才起作用。
So the structure is the following: 因此,结构如下:
@Entity
class A {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "a_id")
long id;
}
@Entity
class B {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "b_id")
long id; // FK to a_id
}
class BDao {
void store(B b) {
session.save(b); // to many places
}
}
Will appriciate any help, thanks! 会给您任何帮助,谢谢!
Yeah! 是的 I've fixed it, just in case somebody wants to know the answer I'm leaving my solution here.
我已解决此问题,以防万一有人想知道答案,而我将解决方案留在这里。 Perhaps you guys will spent less time than me solving the same problem.
也许你们花的时间少于我解决相同问题的时间。 So first you need to use @Inheritance(strategy= InheritanceType.JOINED) annotation to describe the parent entity:
因此,首先您需要使用@Inheritance(strategy = InheritanceType.JOINED)批注来描述父实体:
@Entity
@Inheritance(strategy= InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name = "a_id")
public class A {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "a_id")
protected Integer id;
}
Then describe the child entity like 然后像这样描述子实体
@Entity
@AssociationOverride(name="a_id", joinColumns = @JoinColumn(name="b_id"))
@PrimaryKeyJoinColumn(name = "b_id")
public class B extends A {
...
}
I've left here @AssociationOverride because in my case I have different primary key name so perhaps it helps somebody as well. 我离开这里@AssociationOverride是因为在我的情况下,我使用了不同的主键名称,因此也许对某些人也有帮助。
That's it! 而已! Now when you persist a child entity it will create two rows - one for a parent and one for a child tables.
现在,当您保留一个子实体时,它将创建两行-一行用于父表,另一行用于子表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.