JPA註解@column詳解(附帶小例子)

@Column標記表示所持久化屬性所映射表中的字段,該註釋的屬性定義如下:

@Target({METHOD, FIELD}) @Retention(RUNTIME)

public @interface Column {

    String name() default "";

    boolean unique() default false;

    boolean nullable() default true;

    boolean insertable() default true;

    boolean updatable() default true;

    String columnDefinition() default "";

    String table() default "";

    int length() default 255;

    int precision() default 0;

    int scale() default 0;

}

在使用此@Column標記時,需要注意以下幾個問題:

1. 此標記可以標註在getter方法或屬性前,例如以下的兩種標註方法都是正確的:

標註在屬性前:

@Entity

@Table(name = "contact")

public class ContactEO{

    @Column(name=" contact_name ")

    private String name;

}

標註在getter方法前:

@Entity

@Table(name = "contact")

public class ContactEO{

    @Column(name=" contact_name ")

    public String getName() {

             return name;

    }

}

2.unique屬性表示該字段是否爲唯一標識,默認爲false。如果表中有一個字段需要唯一標識,則既可以使用該標記,也可以使用@Table標記中的@UniqueConstraint


3.nullable屬性表示該字段是否可以爲null值,默認爲true


4.insertable屬性表示在使用“INSERT”腳本插入數據時,是否需要插入該字段的值。


5.updatable屬性表示在使用“UPDATE”腳本插入數據時,是否需要更新該字段的值。insertableupdatable屬性一般多用於只讀的屬性,例如主鍵和外鍵等。這些字段的值通常是自動生成的。


6. columnDefinition屬性表示創建表時,該字段創建的SQL語句,一般用於通過Entity生成表定義時使用。


7.table屬性表示當映射多個表時,指定表的表中的字段。默認值爲主表的表名。有關多個表的映射將在本章的5.6小節中詳細講述。


8.length屬性表示字段的長度,當字段的類型爲varchar時,該屬性纔有效,默認爲255個字符。


9.precision屬性和scale屬性表示精度,當字段類型爲double時,precision表示數值的總長度,scale表示小數點所佔的位數。


下面舉幾個小例子:

示例一:指定字段“contact_name”的長度是“512”,並且值不能爲null

private String name;


@Column(name="contact_name",nullable=false,length=512)

public String getName() {

         return name;

}

創建的SQL語句如下所示。

CREATE TABLE contact (

    id integer not null,

    contact_name varchar (512) not null,

    primary key (id)

)


示例二:指定字段“monthly_income”月收入的類型爲double型,精度爲12位,小數點位數爲2位。

private BigDecimal monthlyIncome;

 

@Column(name="monthly_income",precision=12, scale=2)

public BigDecimal getMonthlyIncome() {

    return monthlyIncome;

}

創建的SQL語句如下所示。

CREATE TABLE contact (

    id integer not null,

    monthly_income double(12,2),

    primary key (id)

)


示例三:自定義生成CLOB類型字段的SQL語句。

private String  name;

 

@Column(name=" contact_name ",columnDefinition="clob not null")

public String getName() {

    return name;

}

生成表的定義SQL語句如下所示。

CREATE TABLE contact (

    id integer not null,

    contact_name clob (200) not null,

    primary key (id)

)

其中,加粗的部分爲columnDefinition屬性設置的值。若不指定該屬性,通常使用默認的類型建表,若此時需要自定義建表的類型時,可在該屬性中設置。


示例四:字段值爲只讀的,不允許插入和修改。通常用於主鍵和外鍵。

private Integer id;

        

@Column(name="id",insertable=false,updatable=false)

public Integer getId() {

    return id;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章