Hibernate和JPA:如何对String进行外键约束 [英] Hibernate and JPA: how to make a foreign key constraint on a String
问题描述
我正在使用Hibernate和JPA.如果我有两个简单的实体:
I am using Hibernate and JPA. If I have two simple entities:
@Entity
@Table(name = "container")
public class Container {
@Id
@Column(name="guid")
private String guid;
}
@Entity
@Table(name="item")
public class Item {
@Id
@Column(name="guid")
private String guid;
@Column(name="container_guid")
private String containerGuid;
}
,并且我想确保如果引用的容器不存在,则无法插入项目.我希望不要在项目对象(ManyToOne)中填充一个Container对象,如果可以的话我该怎么办?
and I want to insure that inserting an Item fails if the referenced Container does not exist. I would prefer not to have a Container object populated inside the item object (ManyToOne), how would I do this if it is possible to do?
推荐答案
您可以使用columnDefinition
属性声明任意约束:
You can declare arbitrary constraint using columnDefinition
attribute:
@Column(name="container_guid",
columnDefinition = "VARCHAR(255) REFERENCES container(guid)")
private String containerGuid;
但是请注意,Hibernate对这个约束一无所知,因此,例如,它可能不会按照正确的顺序执行插入操作,等等.
Note, however, that Hibernate doesn't know anything about this constraint, so that, for example, it may not perform inserts in proper order with respect of it and so on.
因此,最好创建一个@ManyToOne
关系.如果您担心设置此属性需要对Container
进行额外的SQL查询,则可以使用Session.load()
/EntityManager.getReference()
获取代理,而无需发出实际查询.
Therefore it would be better to create a @ManyToOne
relationship. If you are afraid of extra SQL query for Container
needed to set this property, you can use Session.load()
/EntityManager.getReference()
to get a proxy without issuing actulal query.
这篇关于Hibernate和JPA:如何对String进行外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!