Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: Which should I use? Basic(optional) or Column(nullable)?

For simple string field,

@Entity
class Foo {

    //1. @Basic(optional = false)
    //2. @Column(length = 100, nullable = false)
    String name;
}

I need to restrict name's length using @Column annotation, but I'm confused with the nullable attribute. While I'm using other annotations like @ManyToOne and @OneToMany those use optional attributes, I feel like to use @Basic(optional) to keep most annotations uniform. But I can't restrict the name's length with @Basic.

So, where should I annotate the nullable attribute, by @Basic or @Column?

EDIT

Simply say, in which form would you prefer:

Form 1:

@Entity
class Foo {
    @Basic(optional = false)
    @Column(length = 100)
    String name;
}

Form 2:

@Entity
class Foo {
    @Column(length = 100, nullable = false)
    String name;
}

Well personally I like Form 1, because optional attribute is also used by @ManyToOne etc. annotations, but Form 2 is also good because it's done in single annotation.

EDIT

After read http://markmail.org/message/osod6rsauwbnkvya, I've got the difference between @Basic.optional and @Column.nullable. But I still don't know which one I should use. It seems like good to include both annotations, so make the underlying table well defined, and check null in JPA before the actual update maybe slightly faster.

like image 578
Xiè Jìléi Avatar asked Apr 09 '11 04:04

Xiè Jìléi


1 Answers

From API documentation:

@Basic:

@Basic annotation is the simplest type of mapping to a database column. The Basic annotation can be applied to a persistent property or instance variable of any of the following types: Java primitive types, wrappers of the primitive types, String, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp, byte[], Byte[], char[], Character[], enums, and any other type that implements Serializable.

@Column

@Column Is used to specify a mapped column for a persistent property or field. If no Column annotation is specified, the default values are applied.

So, if you don't specify @Column it derives column value from getter/setter. If you need to specify column name you have to @Column annotation.

@Basic allows you to specify Fetch Type. If you want to change default fetching type you have to use this annotation, otherwise you can omit it.

like image 141
Reddy Avatar answered Oct 16 '22 10:10

Reddy