本文介绍了我如何重写使用Hibernate / JPA注解GenerationType策略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的注解来定义我的Hibernate映射,但遇到一个问题考虑

:我想用一个基本实体类定义共同的领域(包括ID字段),但我想不同的表有不同的ID生成策略

  @MappedSuperclass
公共抽象类基本实现Serializable {
    @ID
    @Column(NAME =ID,可为空= FALSE)
    私人整数ID;
    公共整数的getId(){返回ID;}
    公共无效SETID(整数ID){this.id = ID;}
    ...
}@实体
@Table(NAME =TABLE_A)
公共类TableA的扩展基地{
    //表-A要设​​置ID的应用程序定义的值
    ...
}@实体
@Table(NAME =表-B)
公共类表B扩展基地{
    //我要如何ID指定@GeneratedValue(策略= AUTO)在这里?
    ...
}

有没有一些方法来做到这一点?我试过,包括以下内容表B ,但冬眠反对具有相同的列两次我,好像错了:

  @Override //这样我们就可以设置生成策略
@ID
@GeneratedValue(策略= AUTO)
公共整数的getId(){
    返回super.getId();
}


解决方案

在上面的code,它看起来像你的字段(父)和方法(子类)混合注释。 Hibernate的建议避免这一点,我怀疑这可能会造成问题。在我与Hibernate的经验,这是更安全,更灵活的注释getter / setter方法​​,而不是领域无论如何,所以如果可以的话我建议坚持的设计。

作为解决你的问题,我建议从你的基地超完全移除 ID 字段。相反,移动该字段为子类,并创建抽象的的getId() SETID()在你的基类的方法。然后覆盖/实施的getId() SETID()在你的子类方法和所需的生成策略注释干将。

希望这有助于。

I'm considering using Annotations to define my Hibernate mappings but have run into a problem: I want to use a base entity class to define common fields (including the ID field) but I want different tables to have different ID generation strategies:

@MappedSuperclass
public abstract class Base implements Serializable {
    @Id
    @Column(name="ID", nullable = false)
    private Integer id;
    public Integer getId(){return id;}
    public void setId(Integer id){this.id = id;}
    ...
}

@Entity
@Table(name="TABLE_A")
public class TableA extends Base {
    // Table_A wants to set an application-defined value for ID
    ...
}

@Entity
@Table(name="TABLE_B")
public class TableB extends Base {
    // How do I specify @GeneratedValue(strategy = AUTO) for ID here?
    ...
}

Is there some way to do this? I've tried including the following into TableB but hibernate objected to my having the same column twice and it seems wrong:

@Override // So that we can set Generated strategy
@Id
@GeneratedValue(strategy = AUTO)
public Integer getId() {
    return super.getId();
}
解决方案

In the code above, it looks like you're mixing annotations on fields (superclass) and methods (subclass). The Hibernate reference documentation recommends avoiding this, and I suspect it might be causing the problem. In my experience with Hibernate, it's safer and more flexible to annotate getter/setter methods instead of fields anyway, so I suggest sticking to that design if you can.

As a solution to your problem, I recommend removing the id field from your Base superclass altogether. Instead, move that field into the subclasses, and create abstract getId() and setId() methods in your Base class. Then override/implement the getId() and setId() methods in your subclasses and annotate the getters with the desired generation strategy.

Hope this helps.

这篇关于我如何重写使用Hibernate / JPA注解GenerationType策略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 16:53