I have a DateInterval class that is annotated with @Embeddable and it has two persistent fields, startDate and endDate. A DateInterval field may be optional depending on the persistent class that uses it. If the DateInterval field is optional, both of its startDate and endDate should be nullable.
How do I implement this with JPA 2 and/or Hibernate?
If I annotated directly the fields of the DateInterval 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've tried the following, but didn't work.
class Foo {
@Embedded
@Column(nullable = true)
    public DateInterval getDateInterval() {
    }
}
Any suggestions? Thanks!
You should use @AttributeOverride (only one column) or @AttributeOverrides if more than one if you you to override 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; }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With