MappedSuperclass - 在子类中更改SequenceGenerator [英] MappedSuperclass - Change SequenceGenerator in Subclass

查看:239
本文介绍了MappedSuperclass - 在子类中更改SequenceGenerator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JPA2和Hibernate,并尝试为我的实体引入一个公共基类。到目前为止它看起来像:

I'm using JPA2 with Hibernate and try to introduce a common base class for my entities. So far it looks like that:

@MappedSuperclass
public abstract class BaseEntity {

    @Id
    private Long id;

    @Override
    public int hashCode() {
        // ...
    }

    @Override
    public boolean equals(Object obj) {
        // ...
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

但是,每个表都有一个序列 $ entityname_seq 我想用作序列生成器。如何从我的子类中设置它?我想我需要覆盖@GeneratedValue并使用@SequenceGenerator创建一个新的SequenceGenerator。

However, for every table theres a sequence $entityname_seq which I want to use as my sequence generator. How can I set that from my subclass? I think I need to override @GeneratedValue and create a new SequenceGenerator with @SequenceGenerator.

推荐答案

是的,这是可能的。您可以使用 @SequenceGenerator 注释覆盖默认生成器名称。

Yes, it is possible. You can override the default generator name with the @SequenceGenerator annotation.


  • 基类

    @MappedSuperclass
    public abstract class PersistentEntity implements Serializable
    {
        private static final long serialVersionUID = 1L;

        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "default_gen")
        protected Long id = 0L;

        public Long getId()
        {
            return id;
        }

        public void setId(Long id)
        { 
            this.id = id;
        }
    }




  • 序列(SQL)

    • Sequence (SQL)

      create sequence role_seq;


    • 派生类

    • Derived class

          @Entity
          @Table(name = "role")
          @SequenceGenerator(name = "default_gen", sequenceName = "role_seq", allocationSize = 1)
          public class Role extends PersistentEntity implements Serializable
          {
              private static final long serialVersionUID = 1L;
      
              @NotNull
              @Size(max = 32)
              private String name;
      
              public String getName()
              {
                   return name;
              }
      
              public void setName(String name)
              {
                   this.name = name;
              }   
          }




      • 这种方法在Hibernate 4.1中运行良好。 x,但它不在EclipseLink 2.x中。

      • 编辑


        • 根据评论,它似乎与EclipseLink 2.6.1-RC1一起使用。

        这篇关于MappedSuperclass - 在子类中更改SequenceGenerator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆