Tom Tucker
Tom Tucker

Reputation: 11896

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!

Upvotes: 5

Views: 3447

Answers (1)

Arthur Ronald
Arthur Ronald

Reputation: 33775

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

}

Upvotes: 12

Related Questions