@UniqueConstraint check across multiple tables in JPA

hibernate, jpa

Solution

I may be missing something here, but aren't building names unique within a campus as well? So you need to make sure that room names are unique within given building:

@Entity
@Table(name="rooms",
  uniqueConstraints = {@UniqueConstraint(columnNames={"building_id","name"})}
)
public class Room {
  ...
  @ManyToOne
  @JoinColumn(name = "building_id")
  private Building building;
  ...
}

If you now do the same for `Building` names within `Campus`, you should be good to go.

Problem

Campus has @OneToMany Buildings Building has @OneToMany Rooms. Room names needs to be unique within a campus (e.g. campus-A, block-A, room-A and campus-B, block-A, room-A should be possible to store) Would it be possible to define such a unique constraint on the Room entity?

Original source