«

2021年8月4日 JPA使用记录

时间:2021-8-4 23:02     作者:Mahalalel     分类: JPA


1、时间字段设置默认值

@Column(name="CREATE_TIME", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP", insertable = false, updatable = false)
@Generated(GenerationTime.INSERT)
private Date createTime;

解释:
①、columnDefinition:设置默认值以及生成注释
②、GenerationTime:可用选项ALWAYS、INSERT和NEVER;

③、insertable、updatable:设置为false,该属性就不会在insert或者update语句中出现,该属性的值就由数据库默认值设置

2、使用GetMapping获取数据异常解决

2-1、异常如下:

No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer 
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) 
(through reference chain: com.mahalalel.baseproject.entity.OperaterLog$HibernateProxy$JJMDYJDv["hibernateLazyInitializer"])

2-2、原因

spring boot使用jpa查询返回实体后,返回接口时候json格式化出错;
fastxml.jackson将对象转为json报错,发现有些字段为null;
在接口实现类中,使用了getOne(Long id)方法,这个方法返回的是对象的引用。

2-3、解决

在实体类添加如下注解:
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"})

2-4、测试

使用postman访问接口,返回正确数据库数据

3、时间设置

3-1、一般创建时间只会在插入数据的时候,生成数据;更新时间只有在数据更新的时候,设置数据

创建时间字段添加注解@CreatedDate;更新时间字段添加注解@LastModifiedDate

    @Column(name = "create_time")
    @CreatedDate
    private Date createTime;

    @Column(name = "update_time")
    @LastModifiedDate
    private Date updateTime;

3-2、实体类添加监听器注解

@EntityListeners(AuditingEntityListener.class)
public class Entity {

}

3-3、最重要的,需要在启动类中添加启用JPA审计功能的注解

@EnableJpaAuditing
public class ProjectApplication {

}

3-4、经过测试,发现创建数据时,时间可以写入,但是更新时,创建时间仍然会被置为null

故使用第一种方式:

    @Temporal(TemporalType.TIMESTAMP)
    @CreationTimestamp
    @Column(name = "create_time", updatable = false, columnDefinition = "timestamp default current_timestamp comment '创建时间'")
    private Date createTime;

    @Temporal(TemporalType.TIMESTAMP)
    @UpdateTimestamp
    @Column(name = "update_time")
    private Date updateTime;

---未完待续

标签: JPA