0

I would like to define an entity which contains a list of something (for example embeddable) and each of these embeddables have a property active. At once, only one element inside the list is allowed to be active.

How does one implement this in Hibernate?

Edmondo
  • 19,559
  • 13
  • 62
  • 115

2 Answers2

2

If they're functional, I would just implement a check in the functional service which creates and modifies those embeddables, and throw an exception if the constraint isn't verified. It shouldn't be done at the persistence-level.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

As JB Nizet already pointed out in his earlier suggestion, probably you'll be better off implementing this restriction in your service layer.

However, you might be interested in JSR 303: Bean Validation. Hibernate Validator 4 implements it, and with it you can define custom constraints via annotations that will be executed by Hibernate Validator to validate your beans. Please note that you can achieve the same results using other maybe more suitable frameworks, like Spring Validator.

Take a look at this question for an example: Cross field validation with Hibernate Validator (JSR 303). You can also find these links useful:

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161