Can I make an embedded Hibernate entity non-nullable?

André Chalella picture André Chalella · Aug 24, 2009 · Viewed 18.8k times · Source

What I want:

@Embedded(nullable = false)
private Direito direito;

However, as you know there's no such attribute to @Embeddable.

Is there a correct way to do this? I don't want workarounds.

Answer

ChssPly76 picture ChssPly76 · Aug 24, 2009

Embeddable components (or composite elements, whatever you want to call them) usually contain more than one property and thus are mapped to more than one column. The entire component being null can therefore be treated in different ways; J2EE spec does not dictate one way or another.

Hibernate considers component to be NULL if all its properties are NULL (and vice versa). You can therefore declare one (any) of the properties to be not null (either within @Embeddable or as part of @AttributeOverride on @Embedded) to achieve what you want.

Alternatively, if you're using Hibernate Validator you can annotate your property with @NotNull although this will only result in app-level check, not db-level.