【问题标题】:Hibernate ignoring property values from MappedSuperClasses?Hibernate 忽略 MappedSuperClasses 的属性值?
【发布时间】: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 中获取属性值?

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    您将这些字段声明为私有。如果这确实是您想要的(而不是受保护或受包保护),请将这些注释移至 getter。

    在 getter 上添加注释被定义为休眠的最佳实践。 见:Hibernate Annotation Placement Question

    SomeEntity 的实例实际上没有字段“updatedAt”,因为该字段是其超类的私有成员。持久性提供者看到超类需要这些字段的列,但它也看到实例化的具体类没有使用这些列,因为具体类无法“看到”字段“updateAt”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      相关资源
      最近更新 更多