Reputation: 33
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?
Upvotes: 3
Views: 3541
Reputation: 242786
You can declare arbitrary constraint using columnDefinition
attribute:
@Column(name="container_guid",
columnDefinition = "VARCHAR(255) REFERENCES container(guid)")
private String containerGuid;
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 @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.
Upvotes: 6
Reputation: 11
Try using below relationship mapping
RelationShip Mapping
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@ManyToOne()
@ManyToMany()
<> @JoinColumn(name="<>")
Upvotes: -3