我需要用createdDate和updatedDate更新postgres DB,我尝试过使用方法1,但它插入的是空值。当我读到这篇文章时,似乎@prepersist注解在会话中不起作用。
所以我决定采用方法2: Hibernate @CreationTimeStamp Annotation,我添加了hibernate-Annotation maven依赖项,但@CreationTimeStamp没有解析,并给出了编译错误。
有人能建议我如何解决这个问题吗?
方法1使用@Entity和@Table注释的实体类
public class Status{
@Id
@Column(name = "run_id")
private int run_id;
@Column(name = "status")
private String status;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_date" , updatable=false)
private Date created;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_date" , insertable=false)
private Date updated;
@PrePersist
protected void onCreate() {
created = new Date();
}
@PreUpdate
protected void onUpdate() {
updated = new Date();
}
//Getters and setters here
}实现类是
sessionFactory.getCurrentSession().save(status); 方法2使用@CreationTimeStamp和@updatedTimeStamp。但是maven依赖
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-annotations -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.0-Final</version>
</dependency>不会将这些注释添加到类路径中
发布于 2019-09-06 19:07:04
使用session.save()方法而不是使用entitymanager有什么原因吗?我将发布一个使用entitymanager持久化和合并实体的应用程序示例。另外,我使用的是java.time.LocalDateTime而不是java.util.Date,这就是我不需要@Temporal的原因。
如果你想使用Entity管理器,这将会有帮助:Guide to the Hibernate EntityManager Entity How to use @PrePersist and @PreUpdate on Embeddable with JPA and Hibernate:
public abstract class AbstractEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(updatable = false, nullable = false)
private Long id;
@Column
private LocalDateTime createdTimestamp;
@Column
private LocalDateTime modifiedTimestamp;
@Version
private Long version;
@PrePersist
public void setCreationDateTime() {
this.createdTimestamp = LocalDateTime.now();
}
@PreUpdate
public void setChangeDateTime() {
this.modifiedTimestamp = LocalDateTime.now();
}
//Getter and setter
}抽象数据库服务类:
public abstract class AbstractDatabaseService {
@PersistenceContext(name = "examplePU")
protected EntityManager entityManager;
}实体存储库接口示例:
public interface ExampleRepository {
ExampleEntity save(ExampleEntity exampleEntity);
}实体库实现示例:
public class ExampleRepositoryImpl extends AbstractDatabaseService implements ExampleRepository , Serializable {
@Transactional
@Override
public ExampleEntity save(ExampleEntity exampleEntity) {
ExampleEntity toPersist;
// Updating an already existing entity
if (exampleEntity.getId() != null) {
toPersist = entityManager.find(ExampleEntity .class, exampleEntity.getId());
// Omitted merging toPersist with the given exampleEntity through a mapper class here
} else {
toPersist = exampleEntity;
}
try {
toPersist = entityManager.merge(toPersist);
} catch (Exception e) {
// Logging e
}
return toPersist;
}
}希望这能有所帮助。
https://stackoverflow.com/questions/57769936
复制相似问题