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;
}
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?
You can declare arbitrary constraint using
columnDefinitionattribute: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.
Therefore it would be better to create a
@ManyToOnerelationship. If you are afraid of extra SQL query forContainerneeded to set this property, you can useSession.load()/EntityManager.getReference()to get a proxy without issuing actulal query.