gpt4 book ai didi

java - JPA PrePersist 和 PreUpdate

转载 作者:太空宇宙 更新时间:2023-11-04 12:35:54 26 4
gpt4 key购买 nike

我正在使用基本实体:

@MappedSuperclass
public class BaseEntity {
private static final Logger L = LoggerFactory.getLogger(BaseEntity.class);

String id;
String name;
String description;

Date created;
Date updated;

public BaseEntity() {
id = UUID.randomUUID().toString();
}

@PrePersist
protected void onCreate() {
created = new Date();
}

@PreUpdate
protected void onUpdate() {
updated = new Date();
}

@Id
@Column(name = "id", nullable = false)
public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

@Temporal(TemporalType.TIMESTAMP)
public Date getCreated() {
return created;
}

public void setCreated(Date created) {
this.created = created;
}

@Temporal(TemporalType.TIMESTAMP)
public Date getUpdated() {
return updated;
}

public void setUpdated(Date updated) {
this.updated = updated;
}
... snip

然后我有一个实体:

@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.UUIDGenerator.class, property = "@baby_id", scope = Baby.class)
@Table(name="babies")
public class Baby extends BaseEntity {
private static final Logger L = LoggerFactory.getLogger(Baby.class);

Date dob;

public Baby() {
super();
}

public Date getDob() {
return dob;
}

public void setDob(Date dob) {
this.dob = dob;
}
... snip ...

这是我的测试:

@Test
@Transactional
public void testCreateBaby() {
Baby b = new Baby();
b.setName("n");
b.setDescription("baby");
b.setDob(new Date());

assertNull(b.getCreated());
assertNull(b.getUpdated());
em.persist(b);
assertNotNull(b);
assertNotNull(b.getCreated());
assertNull(b.getUpdated());

b.setName("n3");
b = em.merge(b);
em.persist(b);
assertNotNull(b.getUpdated());
}

测试失败,因为 updated 字段未设置。我该怎么做呢?这是使用 arquillian 和 wildfly 进行测试的 Hibernate JPA。

最佳答案

正如 Alan Hay 所说,在这种情况下,持久化之前的 em.flush() 效果很好。这与建议的问题不重复,因为冲洗有效。

关于java - JPA PrePersist 和 PreUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37348564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com