【发布时间】:2014-10-23 15:46:00
【问题描述】:
我的 Hibernate 实体有几个基类:
@MappedSuperclass
public abstract class Entity<T> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private T id;
public T getId() { return this.id; }
}
@MappedSuperclass
public abstract class TimestampedEntity<T> extends Entity<T> {
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at")
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at")
private Date updatedAt;
// Getters and setters for createdAt and updatedAt....
}
每个实体类显然都扩展了这些基类,并获取了id属性以及createdAt和updatedAt属性……
@Entity
public class SomeEntity extends TimestampedEntity<Long> {
// Insert SomeEntity's fields/getters/setters here. Nothing out of the ordinary.
}
我的问题是,当保存 SomeEntity 的新实例时,Hibernate 会忽略超类中的任何属性值。它将尝试为 id 列插入自己的值(这显然与表的标识列不同步)并尝试为 createdAt 和 updatedAt 插入空值,即使它们已肯定设置.
SomeEntity e = new SomeEntity(/* ... */);
e.setCreatedAt(new Date());
e.setUpdatedAt(new Date());
// Here Hibernate runs an INSERT statement with nulls for both createdAt and updatedAt
// as well as a wildly out of sequence value for id
// I don't think it should be trying to insert id at all, since the GenerationType is IDENTITY
Long id = (Long)session.save(e);
我在这里做错了什么?如何让 Hibernate 从 MappedSuperclasses 中获取属性值?
【问题讨论】: