views:

1756

answers:

2

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?

+7  A: 

@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 ayttribute 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.

djna
This is a clear answer. Thank you. So I assume one can use `@Basic` without `@Column`, which is why the `optional` and `nullable` properties exist in both. Am I right?
Hosam Aly
I don't claim to fully understand the JPA spec on the differences between @Basic's nullable and @Column's nullable and the effect of specifying neither, either or both. @Basic nullable is described as a "hint" with relevence to schema generation. @Column nullable is described as defining the characteristics of the column in the database. My practice would be to use the @Column case.
djna
@Basic(optional) is (should be) checked on runtime by persistence provider before saving to DB. @Column is a column definition in database and is used for schema generation : http://stackoverflow.com/questions/2899073/basicoptional-false-vs-columnnullable-false-in-jpa
peperg
+2  A: 

In addition to @djna's answer, it is worth noting that @Basic should be compared with @OneToMany, @ManyToOne and @ManyToMany. Only one of these can be specified on any property. @Column and @JoinColumn can be specified along with any of these to describe the database column properties. These are two sets of annoations that can be used together, but only one annotation of each set can be used at a time.

Hosam Aly