Inheritance @具有实体继承的PrePersist
我在继承和@PrePersist注释方面遇到一些问题。 我的源代码如下所示: _带有带注释的updateDates()方法的“基类”: _现在,应该从基类继承所有方法和注释的“Child”类:Inheritance @具有实体继承的PrePersist,inheritance,jpa,Inheritance,Jpa,我在继承和@PrePersist注释方面遇到一些问题。 我的源代码如下所示: _带有带注释的updateDates()方法的“基类”: _现在,应该从基类继承所有方法和注释的“Child”类: @javax.persistence.Entity @NamedQueries({ @NamedQuery(name=Sensor.QUERY_FIND_ALL, query="SELECT s FROM Sensor s") }) public class Sensor extends Enti
@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
...
}
如果我将基类的实例存储/持久化到数据库中,一切都会正常工作。日期正在更新。
但是现在,如果我想持久化一个子实例,数据库会抛出以下异常:
MySQLIntegrityConstraintViolationException: Column 'CREATIONDATE' cannot be null
因此,在我看来,这是因为在Child中,在将实例持久化到数据库之前,没有调用/调用方法“@PrePersist protected void updateDates()”
我的代码怎么了?我已经用Hibernate作为JPA提供者(和HSQLDB)测试了您的代码。我刚刚在基类中做了以下更改(因为您不能使用
IDENTIY
——HSQLDB的默认值,如果我没有错的话,也可以使用MySQL的默认值——使用TABLE_PER_class
策略1):
通过此变更,以下试验方法通过:
@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提供商
我想了解一下这方面的背景
@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());
}