Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an @Embeddable class optional?

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!

like image 556
Tom Tucker Avatar asked Dec 27 '10 02:12

Tom Tucker


1 Answers

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; }

}
like image 57
Arthur Ronald Avatar answered Oct 22 '22 06:10

Arthur Ronald