Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use @Basic(optional = false) in JPA 2.0

I have a Inheritance with Single Table mapping in JPA, Say Class A and B extends some abstract entity, so I have to make columns from A & B nullable at DB end but if someone is trying to persist A then all fields of A should be not null and i want to enforce this by code. Can I use following code to achieve this -

@Entity  
@DiscriminatorValue("1")  
public Class A extends SomeAbstractEntity{    
     @Basic(optional = false)  
     private String nameOfA;  
}

I read this answer @Basic(optional = false) vs @Column(nullable = false) in JPA and thought this may be achievable but wanted to know what is the best way.

like image 808
Premraj Avatar asked Feb 17 '11 10:02

Premraj


1 Answers

It's quite funny, but it looks like in this case (with single table inheritance) @Basic(optional = false) is not enforced by Hibernate (though in other cases it works as expected).

If so, the only option to enforce this rule is to use @NotNull constraint from JSR-303 Bean Validation. JSR-303 smoothly integrates with JPA 2.0, so that constraints are checked automatically when entities are persisted, see Hibernate Validator.

like image 66
axtavt Avatar answered Oct 06 '22 01:10

axtavt