Spring @Column的注解详解
下文笔者将讲述Spring中@Column注解的功能说明
设置字段“user_name”的长度是“512”,且值不能为null
指定字段“income”月收入的类型为double型,精度为12位,小数点位数为2位
自定义生成CLOB类型字段的SQL语句
字段值为只读的,不允许插入和修改。通常用于主键和外键。
@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注解属性值简介说明
name name属性定义了被标注字段在数据库表中所对应字段的名称 unique unique属性表示该字段是否为唯一标识,默认为false。如果表中有一个字段需要唯一标识,则既可以使用该标记,也可以使用@Table标记中的@UniqueConstraint。 nullable nullable属性表示该字段是否可以为null值,默认为true。 insertable insertable属性表示在使用“INSERT”脚本插入数据时,是否需要插入该字段的值。 updatable updatable属性表示在使用“UPDATE”脚本插入数据时,是否需要更新该字段的值。insertable和updatable属性一般多用于只读的属性,例如主键和外键等。这些字段的值通常是自动生成的。 columnDefinition columnDefinition属性表示创建表时,该字段创建的SQL语句,一般用于通过Entity生成表定义时使用。(也就是说,如果DB中表已经建好,该属性没有必要使用。) table table属性定义了包含当前字段的表名。 length length属性表示字段的长度,当字段的类型为varchar时,该属性才有效,默认为255个字符。 precision和scale precision属性和scale属性表示精度,当字段类型为double时,precision表示数值的总长度,scale表示小数点所占的位数。
@Column注解使用注意事项:
标注在属性前:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class UserEO {
@Column(name = " user_name ")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
标注在getter方法前
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class UserEO {
private String name;
@Column(name = " user_name ")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
例2
设置字段“user_name”的长度是“512”,且值不能为null
private String name;
@Column(name="contact_name",nullable=false,length=512)
public String getName() {
return name;
}
sql建表语句如下
CREATE TABLE user (
id integer not null,
user_name varchar (512) not null,
primary key (id)
)
例2
指定字段“income”月收入的类型为double型,精度为12位,小数点位数为2位
private BigDecimal income; @Column(name="income",precision=12, scale=2) public BigDecimal getIncome() { return income; } sql建表语句 CREATE TABLE user ( id integer not null, income double(12,2), primary key (id) )例3
自定义生成CLOB类型字段的SQL语句
private String name;
@Column(name=" contact_name ",columnDefinition="clob not null")
public String getName() {
return name;
}
sql建表语句
CREATE TABLE user (
id integer not null,
contact_name clob (200) not null,
primary key (id)
)
例4
字段值为只读的,不允许插入和修改。通常用于主键和外键。
private Integer id;
@Column(name="id",insertable=false,updatable=false)
public Integer getId() {
return id;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


