简体   繁体   English

如何制作外键?

[英]How to make a foreign key?

How can I specify a foreign key in hibernate ? 如何在休眠中指定外键?

I have a table A that has id as a column which also forms its primary key. 我有一个表id为列的表A ,它也构成了它的主键。 Now the second table B also has id as the column but it should be the foreign key that references the id column of table A . 现在,第二个表B也具有id作为列,但是它应该是引用table Aid列的foreign key

How can I specify this relation ? 如何指定这种关系?

This example is a one to one relation using shared primary key. 本示例是使用共享主键的一对一关系。 You can use @PrimaryKeyJoinColumn to achieve this. 您可以使用@PrimaryKeyJoinColumn实现此目的。

In Class A 在A级

@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn(name = "ID")
public B getB() {
    return b;
}

In Class B, 在B类中

@Id
@GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "a") })
@GeneratedValue(generator = "gen")
public Long getId() {
    return id;
}


@OneToOne(mappedBy = "a", cascade = CascadeType.ALL)
public B getB() {
    return b;
}

If you're using annotations you must add the relation and the join column with annotations like these: 如果您使用的是注释,则必须使用以下注释添加关系和连接列:

@ManyToOne
@JoinColumn(name="id", nullable=false)
public A getA() {
//...
}

if you're using a mapping xml file it's something like this: 如果您使用的是映射xml文件,则类似于以下内容:

<set name="objects" lazy="true" inverse="true" cascade="all-delete-orphan">
    <key column="ID" />
    <one-to-many class="com.objectx.A" />
</set>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM