Make the @Embeddable class optional?

I have a DateInterval class that is annotated using @Embeddable and has two constant fields: startDate and endDate . The DateInterval field may be optional, depending on the persistent class used. If the DateInterval field is optional, both its startDate and endDate must be NULL.

How to implement this using JPA 2 and / or Hibernate?

If I annotated directly the DateInterval fields, as in the following, then ALL DateInterval fields would not be optional, which is clearly not what I want.

 @Embeddable class DateInterval { @Column(nullable = false) public Date getStartDate() { } } 

I tried the following but did not work.

 class Foo { @Embedded @Column(nullable = true) public DateInterval getDateInterval() { } } 

Any suggestions? Thanks!

+4
source share
1 answer

You should use @AttributeOverride (only one column) or @AttributeOverrides if more than one if you override the default settings

Use instead

 public class Foo { private DateInterval dateInterval; @Embedded @AttributeOverrides({ @AttributeOverride(name="startDate", column=@Column (nullable=true)), @AttributeOverride(name="endDate", column=@Column (nullable=true)) }) public DateInterval getDateInterval() { return this.dateInterval; } public void setDateInterval(DateInterval dateInterval) { this.dateInterval = dateInterval; } } 
+12
source

Source: https://habr.com/ru/post/1333441/


All Articles