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

查看:18
本文介绍了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天全站免登陆