【hibernate】常用注解

【hibernate】常用注解

转载:https://www.cnblogs.com/yangchongxing/p/10357118.html

目录

========================================================

1、@Entity 实体

2、@Table 表

3、@Id 和 @GeneratedValue 主键及生成策略

4、@Column 列

5、@DynamicInsert 和 @DynamicUpdate 动态字段

6、@Immutable 不变实体

7、@Basic 非空约束

8、@NotNull 非空检查

9、@Access 属性访问

10、@Formula 派生属性

11、@ColumnTransformer 转换列值

12、@Generated 默认值

13、@Temporal 时序属性

14、@CreationTimestamp和@UpdateTimestamp 创建时间戳和更新时间戳

15、@Enumerated 枚举类型

16、@Embeddable 可嵌入组件

17、@Lob 大数据类型

18、@Type 类型适配器

19、@Convert 转换器

20、@MappedSuperclass 不持久化超类属性

21、@AttributeOverrides 和 @AttributeOverride 重写属性

22、@Inheritance 继承策略

========================================================

1、@Entity 实体

声明持久化实体,不带 name 参数时表明和实体名相同,带参数重写表明 @Entity(name="ycx_user")

2、@Table 表

重写表名 @Table(name="ycx_user")

3、@Id 和 @GeneratedValue 主键及生成策略

主键和主键生成策略 @GeneratedValue(generator="id_generator") 或者 @GeneratedValue(strategy=GenerationType.SEQUENCE)

4、@Column 列

name="列名"

table=“列属表名”

nullable=false 不能为空,生成非空约束

length=3 字段长度

insertable=false 不包含 INSERT

updatable=false 不包含 UPDATE

列声明 @Column(name="表明", nullable=false),nullable=false 声明数据库非空约束

5、@DynamicInsert 和 @DynamicUpdate 动态字段

动态 SQL 生成,@DynamicInsert 和 @DynamicUpdate,通过启用动态插入和更新,就可以告知 hibernate 在需要时生成 SQL 字符串

6、@Immutable 不变实体

让实体不可变,这样 hibernate 永远不会执行 update 语句,同时可以进行一些优化,比如对不可变类不进行脏检查。

7、@Basic 非空约束

@Basic(optional=false) 声明数据库非空约束

8、@NotNull 非空检查

@NotNull(message="消息内容"),实体非空注解,但是这个在生成数据库结构时会被忽略,在实体保存校验时起作用。

要想在数据库中生成非空约束,必须结合 @Column(nullable=false) 或者 @Basic(optional=false)

9、@Access 属性访问

重写默认的访问行为,字段访问或者属性访问,已经注解过的实体会从强制的 @Id 注解位置继承访问行为,@Id 在字段上则继承字段访问,在 getter 方法上则继承属性访问。

@Access(AccessType.FIELD) 字段访问

@Access(AccessType.PROPERTY) 属性访问

当 @Access 在实体级别设置则会影响实体的所有访问策略,同样 @Access 也可以重写单个属性的访问策略

若默认是字段访问,在字段上添加 @Access(AccessType.PROPERTY) 则被修改为属性访问

若默认是属性访问,在 getter 方法上添加 @Access(AccessType.FIELD) 则被修改为字段访问

10、@Formula 派生属性

运行时通过 @Formula 估算出来,不会出现在 UPDATE 和 INSERT 中,只会出现在 SELECT 中,可以包含 SQL 函数和子查询。

例如 数据库中没有全名而实体中有 @Formula("concat(firstname,'-',lastname)")

11、@ColumnTransformer 转换列值

数据库中存储重量 weight 单位是克,实体中使用千克

@Column(name="weight")
    @org.hibernate.annotations.ColumnTransformer(read="weight / 1000",write="? * 1000")
    protected int kilogramWeight;

12、@Generated 默认值

自动刷新数据库生成的值,如触发器在每次插入和更新后更新的值。使用 @Generated 注解在每次执行 INSERT 和 UPDATE 后委托给 Hibernate 自动查询。

比如插入用户后给一个默认国籍

触发器

BEGIN
set new.nationality = 'CN';
END

java

    @Column(insertable=false,updatable=false)
    @org.hibernate.annotations.ColumnDefault("'CN'") //在 Hibernate 导出 SQL 架构 DDL 时设置列的默认值
    @org.hibernate.annotations.Generated(org.hibernate.annotations.GenerationTime.INSERT)
    protected String nationality;

测试

    @Test
    public void testInsert() {
        this.session.beginTransaction();
        User u = new User();
        u.setUsername("admin");
        u.setFirstname("Tom");
        u.setLastname("Green");
        u.setKilogramWeight(62);
        this.session.persist(u);
        this.session.getTransaction().commit(); //事务提交后才能得到最新的值
        System.out.println(u.getId() + " Hibernate 自动刷新数据库触发器生成的值:" + u.getNationality());
        assertTrue( true );
    }

 13、@Temporal 时序属性

JPA 规范要求使用 @Temporal 注解时序属性,以声明所映射列的准确 SQL 数据库类型。当没有提供时 Hibernate 会默认使用 TemporalType.TIMESTAMP。

Java时序类型 java.util.Date;、java.util.Calendar;、java.sql.Date;、java.sql.Time;、java.sql.Timestamp;

TemporalType 选项 DATE、TIME、TIMESTAMP

14、@CreationTimestamp和@UpdateTimestamp 创建时间戳和更新时间戳

当没有提供 @Temporal 时 Hibernate 会默认使用 TemporalType.TIMESTAMP

    @Temporal(TemporalType.TIMESTAMP)
    @Column(updatable=false)
    @org.hibernate.annotations.CreationTimestamp
    protected Date createOn;
    @Temporal(TemporalType.TIMESTAMP)
    @Column(insertable=false)
    @org.hibernate.annotations.UpdateTimestamp
    protected Date updateOn;

 当执行插入时 Hibernate 自动给 createOn 赋值,当执行更新时 Hibernate 自动给 updateOn 赋值。

15、@Enumerated 枚举类型

默认 Hibernate 会存储 EnumType.ORDINAL 位置,这种很脆弱。EnumType.STRING 存储枚举值的标签,这样变更不会影响

    @Enumerated(EnumType.STRING)
    private Sex sex;

 16、@Embeddable 可嵌入组件

@Embeddable
public class Address {
    @NotNull
    @Column(nullable=false)
    protected String street;
    
    @NotNull
    @Column(nullable=false)
    protected String zipcode;
    
    @NotNull
    @Column(nullable=false)
    protected String city;
    
    public Address() {}
    public Address(String street,String zipcode,String city) {
        this.street = street;
        this.zipcode = zipcode;
        this.city = city;
    }
    @Override
    public String toString() {
        return "Address [street=" + street + ", zipcode=" + zipcode + ", city=" + city + "]";
    }
}

嵌入式组件

    protected Address address;

重写嵌入式组件

    @AttributeOverrides({
        @AttributeOverride(name="street",column=@Column(name="billing_street")),
        @AttributeOverride(name="zipcode",column=@Column(name="billing_zipcode")),
        @AttributeOverride(name="city",column=@Column(name="billing_city"))
    })
    protected Address billingAddress;

 17、@Lob

二进制数据和大数据

18、@Type 类型适配器

    @org.hibernate.annotations.Type(type="yes_no")
    protected boolean verify;
    @org.hibernate.annotations.Type(type="true_false")
    protected boolean verify;

 19、@Convert 转换器

    @Convert(converter = MoneyConverter.class,disableConversion=false)
    protected Money money;

 20、@MappedSuperclass 不持久化超类属性

使用 @Entity 映射具体类,要想超类的属性被忽略并且不持久化,则必须使用  @MappedSuperclass

21、@AttributeOverrides 和 @AttributeOverride 重写属性

子类重写从父类继承的字段和属性

类重写嵌入式字段和属性

 22、@Inheritance 继承策略

@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) 每个带有联合的具体类使用一个表

@Inheritance(strategy=InheritanceType.SINGLE_TABLE) 每个类层次结构使用一个表

@Inheritance(strategy=InheritanceType.JOINED)

posted @ 2019-02-09 06:49  翠微  阅读(2580)  评论(0编辑  收藏  举报