本文共 2329 字,大约阅读时间需要 7 分钟。
父类用于存储子类和父类的公共字段,子类与父类之间存在一一对应关系,子类的id字段通常会参考父类的id字段。
@MappedSuperclass注解只能标准在类上(@Target({java.lang.annotation.ElementType.TYPE}))。
标注为@MappedSuperclass的类并不是完整的实体类,它不会映射到数据库表,但其属性会映射到其子类的数据库字段中。
标注为@MappedSuperclass的类不能再标注@Entity或@Table注解,也无需实现序列化接口。
@PreUpdate注解用于为相应的生命周期事件指定回调方法,可应用于实体类、映射超类或回调监听器类的方法。
示例:每次更新时自动更新更新时间字段。
/** * 修改日期 */ protected Date updateDate; @Column(name = "update_date") public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } @PreUpdate public void preUpdate() { this.setUpdateDate(new Date()); } @PrePersist注解可以用于在使用JPA时记录一些业务无关的字段,如创建日期和最后更新时间等。
示例:自动更新创建时间和更新时间。
/** * 创建日期 */ protected Date createDate; /** * 修改日期 */ protected Date updateDate; @Column(name = "create_date", updatable = false) public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } @Column(name = "update_date") public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } //自动更新创建时间和更新时间 @PrePersist public void prePersist() { if(this.createDate == null){ this.setCreateDate(new Date()); } this.setUpdateDate(new Date()); } 当MySQL字段类型为timestamp时,建议在实体类上加上@DynamicUpdate注解以确保实体类在更新时会更新更新时间字段。
通过@GenericGenerator注解可以定义自定义的生成策略。
@Id @GeneratedValue(generator = "fsId") @GenericGenerator(name = "fsId", strategy = "com.fs.AssignedGUIDGenerator")
package com.fs; import org.hibernate.HibernateException;import org.hibernate.engine.spi.SharedSessionContractImplementor;import org.hibernate.id.IdentifierGenerator;import org.hibernate.id.UUIDHexGenerator; import java.io.Serializable; public class AssignedGUIDGenerator extends UUIDHexGenerator implements IdentifierGenerator{ @Override public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException { Serializable id = session.getEntityPersister(ENTITY_NAME, object).getIdentifier(object, session); if (id==null || id.toString().equals("")) { id = super.generate(session,object); } return id; }} 转载地址:http://xmulz.baihongyu.com/