gpt4 book ai didi

inheritance - @PrePersist 与实体继承

转载 作者:行者123 更新时间:2023-12-04 12:25:24 31 4
gpt4 key购买 nike

我在继承和 方面遇到了一些问题@PrePersist 注解。
我的源代码如下所示:

_带有带注释的 updateDates() 方法的“基”类:

@javax.persistence.Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Base implements Serializable{

...

@Id
@GeneratedValue
protected Long id;
...
@Column(nullable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
@Column(nullable=false)
@Temporal(TemporalType.TIMESTAMP)
private Date lastModificationDate;
...
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getLastModificationDate() {
return lastModificationDate;
}
public void setLastModificationDate(Date lastModificationDate) {
this.lastModificationDate = lastModificationDate;
}
...
@PrePersist
protected void updateDates() {
if (creationDate == null) {
creationDate = new Date();
}
lastModificationDate = new Date();
}
}

_ 现在是应该继承所有方法的“子”类 “和注释”从基类:
@javax.persistence.Entity
@NamedQueries({
@NamedQuery(name=Sensor.QUERY_FIND_ALL, query="SELECT s FROM Sensor s")
})
public class Sensor extends Entity {
...
// additional attributes
@Column(nullable=false)
protected String value;
...
// additional getters, setters
...
}

如果我将 Base 类的实例存储/持久化到数据库,则一切正常。日期正在更新。
但是现在,如果我想持久化一个子实例,数据库会抛出以下异常:
MySQLIntegrityConstraintViolationException: Column 'CREATIONDATE' cannot be null

所以,在我看来,这是因为在 Child 中,在将实例持久化到数据库之前,没有调用/调用方法“@PrePersist protected void updateDates()”。

我的代码有什么问题?

最佳答案

我已经使用 Hibernate 作为 JPA 提供程序(和 HSQLDB)测试了您的代码。我刚刚在基类中进行了以下更改(因为您不能使用 IDENTIY - HSQLDB 的默认值,如果我没记错的话,也可以用于 MySQL - 使用 TABLE_PER_CLASS 策略1):

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
protected Long id;

通过此更改,以下测试方法通过:
@Test
public void test_Insert_EntityWithInheritedPrePersist() {
EntityWithInheritedPrePersist child = new EntityWithInheritedPrePersist();
child.setValue("test");
entityManager.persist(child);

assertEquals(child.getId(), Long.valueOf(1l));
assertNotNull(child.getCreationDate());
assertNotNull(child.getLastModificationDate());
}

所以 @PrePersist在继承的类中调用带注释的方法。

这就引出了一个问题:您使用哪个 JPA 提供程序?

1 见 this thread这方面的背景。

关于inheritance - @PrePersist 与实体继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2552645/

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