5

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.

Community
  • 1
  • 1
Premraj
  • 7,802
  • 8
  • 45
  • 66
  • I've found too many corner cases where the implementation (hibernate) doesn't really do what the standard seems to say. So even if you theoretically can, testing is the only way to make sure. – wds Feb 17 '11 at 11:45
  • oh.. really? can you give few examples? – Premraj Feb 17 '11 at 11:51
  • Take a look at this [site](http://javabrains.koushik.org/p/hibernate.html) Videos 17-20 are about inheritance. I recommend seeing all videos there. – nkvnkv Sep 18 '12 at 17:14

1 Answers1

2

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.

axtavt
  • 239,438
  • 41
  • 511
  • 482