@Basic(optional = false) vs @Column(nullable = false) in JPA

后端 未结 2 528

What\'s the difference between @Basic(optional = false) and @Column(nullable = false) in JPA persistence?

2条回答
  •  Happy的楠姐
    2020-11-29 18:46

    So I tried the @Basic(optional=false) annotation using JPA 2.1 (EclipseLink) and it turns out the annotation is ignored in actual usage (at least for a String field). (e.g. entityManager.persist calls).

    So I went to the specification and read up about it. Here is what the spec has to say:
    http://download.oracle.com/otndocs/jcp/persistence-2.0-fr-oth-JSpec/

    Basic(optional): Whether the value of the field or property may be null. This is a hint and is disregarded for primitive types; it may be used in schema generation.

    So I think this sentence explains the real use case for Basic(optional) it is used in schema generation. (That is: when you generate CREATE TABLE SQL from Java Entity classes. This is something Hibernate can do for example.)

提交回复
热议问题