一个Java小白的学习之路 个人博客 youngljx.top
@MappedSuperclass
在进行实体类的封装时,有时候几张表中可能有很多的共同属性。每次都去建立不同的类很麻烦。这个时候可以建立一个共同属性的类,让其他类去继承这个类。然后映射到数据表中,例如编号ID,创建者,创建时间,修改者,修改时间,备注等。
使用环境:
1.@MappedSuperclass注解使用在父类上面,是用来标识父类的
2.@MappedSuperclass标识的类表示其不能映射到数据库表,因为其不是一个完整的实体类,但是它所拥有的属性能够隐射在其子类对用的数据库表中
3.@MappedSuperclass标识的不能再有@Entity或@Table注解,也无需实现序列化接口
@CreatedDate
, @LastModifiedDate
等
实现自动更新实体创建时间和修改时间
1、在实体类上加上注解 @EntityListeners(AuditingEntityListener.class)
在相应的字段上添加对应的时间注解 @LastModifiedDate
和 @CreatedDate
/**
* @author: Mr.Liu
* @description: 描述实体类的公共配置
* @date: 2020-03-11 12:58
*/
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class) //用于监听实体类添加或者删除操作
public class BaseBean {
/**
* @Description: 自增长id
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* @Description:创建时间
*/
@CreatedDate
@Column(nullable = false ,updatable = false)
//updatable = false表示不进行更新操作 否则更新数据时会出现createTime变为null
private Date createTime;
/**
* @Description: 修改时间
*/
@LastModifiedDate
@Column(nullable = false)
private Date modifyTime;
/**
* @Description: 创建人
*/
@CreatedBy
private Integer createBy;
/**
* @Description: 最后修改人
*/
@LastModifiedBy
private Integer lastModifiedBy;
}
2、在Application启动类中添加注解 @EnableJpaAuditing
@EnableJpaAuditing
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
配置实现AuditorAware接口,以获取字段需要插入的信息:
@Configuration
public class AuditorConfig implements AuditorAware<Integer> {
/**
* 返回操作员标志信息
*
* @return
*/
@Override
public Optional<Integer> getCurrentAuditor() {
// 这里应根据实际业务情况获取具体信息
return Optional.of(new Random().nextInt(1000));
}
}
另外数据库添加相应控制也可以实现:
createTime : CURRENT_TIMESTAMP
modifyTime : CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
补充:
Hibernate 也提供了类似上述时间注解的功能实现,这种方法只需要一步配置,
更改为注解 @UpdateTimestamp
和 @CreationTimestamp
即可:
@Data
@MappedSuperclass
@NoArgsConstructor
@AllArgsConstructor
public class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@UpdateTimestamp
@Column(nullable = false)
private Date updateTime;
@CreationTimestamp
@Column(nullable = false, updatable = false)
private Date createTime;
@NotNull
private Boolean deleted = false;
}
参考 Spring Data JPA 的时间注解:@CreatedDate 和 @LastModifiedDate
Hibernate @Temporal()
注解的使用
Temporal注解的作用就是帮Java的Date类型进行格式化,一共有三种注解值:
第一种:@Temporal(TemporalType.DATE)——>实体类会封装成日期“yyyy-MM-dd”的 Date类型。
第二种:@Temporal(TemporalType.TIME)——>实体类会封装成时间“hh-MM-ss”的 Date类型。
第三种:@Temporal(TemporalType.TIMESTAMP)——>实体类会封装成完整的时间“yyyy-MM-dd hh:MM:ss”的 Date类型
写在字段上:
@Temporal(TemporalType.TIMESTAMP)
private Date birthday;
写在 getXxx方法上:
@Temporal(TemporalType.DATE)
@Column(name = "birthday", length = 10)
public Date getBirthday() {
return this.birthday;
}
参考 https://www.cnblogs.com/meng-ma-blogs/p/8474175.html