11

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.

Lenik
  • 13,946
  • 17
  • 75
  • 103
  • 1
    possible duplicate of [@Basic(optional = false) vs @Column(nullable = false) in JPA](http://stackoverflow.com/questions/2899073/basicoptional-false-vs-columnnullable-false-in-jpa) – rds Jun 18 '13 at 09:34

1 Answers1

10

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.

0x6C38
  • 6,796
  • 4
  • 35
  • 47
Reddy
  • 8,737
  • 11
  • 55
  • 73
  • 3
    See http://stackoverflow.com/questions/2899073/basicoptional-false-vs-columnnullable-false-in-jpa – Reddy Apr 09 '11 at 05:19
  • @Reddy - So, only `@Basic` is like saying that make the database column `NOT NULL` for said variable ? Then why have two ways of doing the same thing ? – Erran Morad May 10 '14 at 00:13