2

To specify a UniqueConstraint on multiple columns, i use the @Table annotation and specify the value for uniqueConstraint. I would also like to add a null constraint based on this scenario:

@Entity
public class Contact{
  private PhoneBook phoneBook;
  private ContactGroup group;
}

An entity can either be in a phoneBook, or in a group but not both, since a group already has a reference to phonebook it belongs to. In this case, both phonebook and group must both not be null and must both not be set, only one can be set at a time.

Working on netbeans 7.2, glassfish 3.2 eclipselink 2.0

Thanks.

maress
  • 3,533
  • 1
  • 19
  • 37
  • I dont think you can do this in JPA. To get around this in the past I have checked this in the business logic and also added check constraint to my DB so that they cannot both be set – RNJ Sep 11 '12 at 10:03

2 Answers2

0
import javax.validation.constraints.NotNull;

@Entity
public class Contact{

  @NotNull
  private PhoneBook phoneBook;

  @NotNull
  private ContactGroup group;
}

Should work :)

EDIT:

I'm sorry, now I see you writing about cross validation, probably you have to write your own validator.

chris
  • 669
  • 9
  • 16
0

I would simply throw ConstraintViolationException in the setter of phoneBook or group depending on the condition.

Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72