简体   繁体   English

如何在休眠状态下不继承Id GeneratedValue(在子类中禁用@GeneratedValue)

[英]How to not inherite Id GeneratedValue in hibernate (disable @GeneratedValue in child class)

I have a hibernate entity Super Class: 我有一个休眠实体超级类:

@MappedSuperclass
public abstract class Pojo_Entity_SuperClass 
{
   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   @Column(name="ID", unique=true, nullable=false, precision=18, scale=0)
   protected long id;
   public Long getId() {return id;}

   //Other entity fields and methods
}

Next I inherite other entity classes like this: 接下来,我继承这样的其他实体类:

@Entity
@Table(name="USR")
public class Usr extends Pojo_Entity_SuperClass 
{
   //Columns, fileds and others
}

But in some cases I want to inherit entity with "id" field without @GeneratedValue annotation. 但是在某些情况下,我想继承不带@GeneratedValue注释的“ id”字段实体。 The question is - how to disable @GeneratedValue annotation for id in child class ? 问题是-如何在子类中为id禁用@GeneratedValue注释?

You can simply move the @Id from the base class to the sub-classes and then decide the generation strategies. 您可以简单地将@Id从基类移动到子类,然后确定生成策略。

So you can have: 因此,您可以:

@MappedSuperclass
public abstract class Pojo_Entity_SuperClass 
{   
    public abstract Long getId();

    public abstract void setId(Long id);

    //Other entity fields and methods
}

@Entity
@Table(name="USR")
public class Usr extends Pojo_Entity_SuperClass {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ID", unique=true, nullable=false, precision=18, scale=0)
    protected long id;  
}

@Entity
@Table(name="ADMIN")
public class Admin extends Pojo_Entity_SuperClass {
    @Id
    @SequenceGenerator(name = "ID_GENERATOR", sequenceName = "admin_id_seq")
    @GeneratedValue(generator = "ID_GENERATOR")
    @Column(name="ID", unique=true, nullable=false, precision=18, scale=0)
    protected long id;  
}

Is this what you need? 这是您需要的吗?

Alternatively, you perhaps actually don't want to avoid inheritance. 另外,您实际上可能不想避免继承。 I tried to do the same before I realized I wanted to create User entity with id from external system and force this id as id in my system. 在意识到我想从外部系统创建ID为ID的User实体并在我的系统中将该ID强制为ID之前,我尝试执行相同的操作。 Since entities are otherwise created with our id, common ancestor with id and sequence generator is valid solution while User with external id would be nonsystematic. 由于以其他方式使用我们的ID创建实体,因此具有ID和序列生成器的公共祖先是有效的解决方案,而具有外部ID的User是非系统的。

Hence it was IMHO cleaner to generate id of User just as in any other case and add another column external_id to table and entity class. 因此,像在任何其他情况下一样,生成User ID都是IMHO清洁器,然后将另一列external_id添加到表和实体类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM