0

I have an @Embeddable class with two fields: type and value. Both fields map to the corresponding database columns. The first one is enum and the latter one is an interface that has multiple implementations.

Only certain combinations of type and value are considered valid even if type and value are correct in isolation. How can I perform such validation, when I retrieve the entity that owns the @Embeddable from the database?

I could perform validation inside no-args-constructor of embeddable, but as far as I'm concerned, Hibernate creates new @Embeddable instance with no-args-constructor and then injects the values with Java Reflection API. Therefore, if I access these two fields inside the constructor they will be null.

Is there an approach to register some PostLoad hook for the @Embeddable classes that Hibernate will trigger? I though about declaring PostLoad inside the entity itself and then calling MyEmbeddable.validate directly. But I think it's a dirty approach.

Semyon Kirekov
  • 1,237
  • 8
  • 20
  • Why not make sure that the combination is valid before inserting? – XtremeBaumer Dec 01 '22 at 12:13
  • @XtremeBaumer Of course, I do such validations before inserting. Anyway, I still want to be sure that I read correct data. Because there are already some rows in the database, when I implement this feature. – Semyon Kirekov Dec 01 '22 at 12:14
  • I think I found possible solution. Will try to implement it https://stackoverflow.com/questions/2781771/how-can-i-validate-two-or-more-fields-in-combination – Semyon Kirekov Dec 01 '22 at 12:23

1 Answers1

0

I added the class-level annotation to validate the whole object. It did work. Check out this question for more details.

Semyon Kirekov
  • 1,237
  • 8
  • 20