Reputation: 121
Let's say I have an entity like this:
@Entity
public Foo {
@Id
private Long id;
private String name;
private String type;
...
}
Is there a way to express that name and type should be unique together? Meaning that for example you could have name "x" with type "y" and name "x" with type "z", but not an other "x" with type "y".
@EmbeddedId doesn't do the trick since name can be changed later - type however remains the same throughout the lifecycle of the entity.
Upvotes: 2
Views: 662
Reputation: 279970
You can add Constraints for your Entity on the @Table
annotation. In your case, you want to make two joined fields unique. You would use the @UniqueConstraint
annotation.
@Entity
@Table(uniqueConstraints=
@UniqueConstraint(columnNames = {"name", "type"})
public Foo {
@Id
private Long id;
@Column
private String name;
@Column
private String type;
...
}
Take a look at the javadoc for @UniqueConstraint
.
Upvotes: 2