Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make an embedded Hibernate entity non-nullable?

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.

like image 779
André Chalella Avatar asked Aug 24 '09 19:08

André Chalella


People also ask

How set NOT NULL in Hibernate?

The @Column(nullable = false) annotation only adds a not null constraint to the table definition. Hibernate or any other framework will not perform any validation on the entity attribute. Hibernate just executes the SQL UPDATE statement, and the database will validate the constraint.

Can Embedded be null?

Hibernate sets the field in the parent object to null. Even if this field is declared final and initialized.

What is nullable true in Hibernate?

The "nullable" attribute of the @Column notation isn't for Hibernate/JPA, it's for the database. Specifically, when using the option to generate a schema, it assures that the "NULLABLE" property is assigned to the corresponding database table column (field).

What does nullable false mean?

The @Column(nullable = false) Annotation It's used mainly in the DDL schema metadata generation. This means that if we let Hibernate generate the database schema automatically, it applies the not null constraint to the particular database column.


2 Answers

It is possible to use "hibernate.create_empty_composites.enabled" since Hibernate 5.1 to change this behavior (see https://hibernate.atlassian.net/browse/HHH-7610 )

like image 42
user158037 Avatar answered Nov 13 '22 15:11

user158037


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.

like image 104
ChssPly76 Avatar answered Nov 13 '22 16:11

ChssPly76