@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標記時,需要注意以下幾個問題:
l 此標記可以標注在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;
}
}
提示:JPA規范中並沒有明確指定那種標注方法,只要兩種標注方式任選其一都可以。這根據個人的喜好來選擇,筆者習慣使用第二種方法。
l unique屬性表示該字段是否為唯一標識,默認為false。如果表中有一個字段需要唯一標識,則既可以使用該標記,也可以使用@Table標記中的@UniqueConstraint。
l nullable屬性表示該字段是否可以為null值,默認為true。
l insertable屬性表示在使用“INSERT”腳本插入數據時,是否需要插入該字段的值。
l updatable屬性表示在使用“UPDATE”腳本插入數據時,是否需要更新該字段的值。insertable和updatable屬性一般多用於只讀的屬性,例如主鍵和外鍵等。這些字段的值通常是自動生成的。
l columnDefinition屬性表示創建表時,該字段創建的SQL語句,一般用於通過Entity生成表定義時使用。
l table屬性表示當映射多個表時,指定表的表中的字段。默認值為主表的表名。有關多個表的映射將在本章的5.6小節中詳細講述。
l length屬性表示字段的長度,當字段的類型為varchar時,該屬性才有效,默認為255個字符。
l 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屬性設置的值。若不指定該屬性,通常使用默認的類型建表,若此時需要自定義建表的類型時,可在該屬性中設置。
提示:通過Entity定義生成表,還是通過表配置Entity,這兩種ORM的策略。有關兩種方法的映射策略好壞,將在本書的章節中“JPA工具的使用”一章進行詳細的比較。
示例四:字段值為只讀的,不允許插入和修改。通常用於主鍵和外鍵。
private Integer id;
@Column(name="id",insertable=false,updatable=false)
public Integer getId() {
return id;
}