JPA实体类@Entity

JPA实体类@Entity
JPA对象注解
@Table - 映射表名
@Id - 主键
@GeneratedValue(strategy=GenerationType.IDENTITY) - 自动递增生成
@Column(name = “dict_name”,columnDefinition=“varchar(100) COMMENT ‘字典名’”) - 字段名、类型、注释
@UpdateTimestamp - 更新时自动更新时间
@CreationTimestamp - 创建时自动更新时间
@Version - 版本号,更新时自动加1
用法:

@Entity
@Table(name="c_user")
public class User {

	@Id
        @GeneratedValue
        private Long id;

        @NotNull
        @Column(length = 50)
        private String userName;

        @NotNull
        @Column(length = 20 , unique = true, nullable = false)
        private Long mobile;

        @Column(length = 20 , unique = true)
        private String email;

        @NotNull
        @Column(columnDefinition="tinyint")
        private Integer status;

        private String password;
        private String nickname;
        private Integer companyId;
        private Integer departmentId;
        private Date regTime;
        private String regIp;
        private Integer loginNum;
     ...
}

@Table
@Table注解用来标识实体类与数据表的对应关系,默认和类名一致。

@Column
@Column注解来标识实体类中属性与数据表中字段的对应关系。共有10个属性,这10个属性均为可选属性:

name属性定义了被标注字段在数据库表中所对应字段的名称;
unique属性表示该字段是否为唯一标识,默认为false。如果表中有一个字段需要唯一标识,则既可以使用该标记,也可以使用@Table标记中的@UniqueConstraint。
nullable属性表示该字段是否可以为null值,默认为true。如果属性里使用了验证类里的@NotNull注释,这个属性可以不写。
insertable属性表示在使用“INSERT”脚本插入数据时,是否需要插入该字段的值。
updatable属性表示在使用“UPDATE”脚本插入数据时,是否需要更新该字段的值。insertable和updatable属性一般多用于只读的属性,例如主键和外键等。这些字段的值通常是自动生成的。
columnDefinition属性表示创建表时,该字段创建的SQL语句,一般用于通过Entity生成表定义时使用。若不指定该属性,通常使用默认的类型建表,若此时需要自定义建表的类型时,可在该属性中设置。(也就是说,如果DB中表已经建好,该属性没有必要使用。)
table属性定义了包含当前字段的表名。
length属性表示字段的长度,当字段的类型为varchar时,该属性才有效,默认为255个字符。
precision属性和scale属性表示精度,当字段类型为double时,precision表示数值的总长度,scale表示小数点所占的位数。
可以标注在getter方法或属性前:
标注在属性前:

@Column(name = " c_name ") 
private String name; 

public String getName() { 
return name; 
} 

标注在getter方法前:

private String name; 

@Column(name = " c_name ") 
public String getName() { 
return name; 
} 

例子:
指定字段“contact_name”的长度是“512”,并且值不能为null。

@Column(name="ct_name",nullable=false,length=512) 
private String name; 

指定字段“price”月收入的类型为double型,精度为12位,小数点位数为2位。

@Column(name="price",precision=12, scale=2) 
private BigDecimal price; 

字段的默认值
很简单声明的时候直接赋值即可:

@Column(columnDefinition="tinyint")
private Integer status = 1;

还有另外一种写法:

@Column(name="state", nullable=false, columnDefinition="tinyint default 0")
private Interger state;

版权声明:本文为weixin_36873225原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。