Java Persistence / JPA: @Column vs @Basic

javajpapersistence

What is the difference between @Column and @Basic annotations in JPA? Can they be used together? Should they be used together? Or does one of them suffice?

Best Answer

  • @Basic signifies that an attribute is to be persisted and a standard mapping is to be used. It has parameters which allow you to specify whether the attribute is to be lazily loaded and whether it's nullable.

  • @Column allows you to specify the name of the column in the database to which the attribute is to be persisted.

If you specify one without the other then you get default behaviour which is sensible, so commonly folks use only one with the exception of special cases.

So if we wanted a lazy loading of an attribute and to specify a column name we can say

 @Basic(fetch=FetchType.LAZY)
 @Column(name="WIBBLE")

If we neeed the default, non-lazy behaviour then just the @Column would have been sufficient.