简体   繁体   中英

Hibernate and JPA: how to make a foreign key constraint on a String

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 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.

Try using below relationship mapping

RelationShip Mapping @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@ManyToOne() @ManyToMany()

<> @JoinColumn(name="<>")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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