Hibernate Session.save 问题

发布于 2024-12-07 17:48:31 字数 513 浏览 0 评论 0原文

您好,我有一个域对象,可以说 Student 及其 Roll 号作为主键,

这里是它的示例映射。

    @Id
@Column(name = "Roll_NO", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Roll_NO_SEQ")
@SequenceGenerator(name = "Roll_NO_SEQ", sequenceName = "Roll_NO_SEQ", allocationSize = 1)
public Long getRollNo() {
    return this.rollNo;
}

问题:假设某个学生从数据库中删除,然后在重新录取时重新录取,我想保留旧的卷号。因此,当我调用 session.save 时,休眠会根据指定的序列分配一个新的卷号,而不是我通过 setRollNo() 方法设置的值。有什么办法可以在休眠中实现这一目标吗?

Hi I have a domain object lets say Student and its Roll no as a primary key

here is the sample mapping for it.

    @Id
@Column(name = "Roll_NO", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Roll_NO_SEQ")
@SequenceGenerator(name = "Roll_NO_SEQ", sequenceName = "Roll_NO_SEQ", allocationSize = 1)
public Long getRollNo() {
    return this.rollNo;
}

issue : lets say if a particular student was deleted from the database, and then re-admitted at the time of re-admission i want to retain the old roll no . so when i call session.save hibernate assigns a new roll No based on the Sequence specified rather then what i am setting through setRollNo() method. is there any way to achieve this in hibernate?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

败给现实 2024-12-14 17:48:31

不要删除记录,添加一个名为 soemthign 的新布尔字段,如 activevalid,而不是删除,只需设置 active = false

或者,

您可以将要删除的记录插入到存档表中,然后删除,然后从那里查找。

don't delete the record, add a new boolean field called soemthign like active or valid, and instead of deleting just make active = false.

Or,

You could insert the record to be deleted into an archive table and then delete, and then look up from there.

人生百味 2024-12-14 17:48:31

鉴于您无法更改遗留代码,Ryan 的想法是正确的。前段时间我在个人项目中不得不做基本上相同的事情。有两个部分:简单的部分是允许有效设置其他自动编号列的 ID...另一个部分是在您转到 Save() 时使 ID 生成器停止覆盖该值。

这是我使用的FlexibleIDGenerator的代码:

public class FlexibleIDGenerator extends IdentityGenerator implements Configurable {
   public static final String DEFAULT = "default";

   private IdentifierGenerator assignedGenerator;
   private IdentifierGenerator defaultGenerator;

@SuppressWarnings("unchecked")
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
      //boolean useDefault = false;

      if (object instanceof OverridableIdentity) {
          if (((OverridableIdentity) object).isIDOverridden()) {
              try {
                  Class cl = object.getClass().getSuperclass();
                  Method[] methods = cl.getDeclaredMethods();

                  for (int i = 0; i < methods.length; i++) {
                      if (methods[i].getName().equalsIgnoreCase("setId")) {
                          methods[i].invoke(object, Integer.valueOf((((OverridableIdentity) object).getOverriddenID())));
                      }
                  }
              } catch (Exception ex) {
                  ex.printStackTrace();
              }
              return assignedGenerator.generate(session, object);
          } else {
              return defaultGenerator.generate(session, object);
          }
      } else {
          return defaultGenerator.generate(session, object);
      }
   }

   public void configure(Type type, Properties params, Dialect d) throws MappingException {
      assignedGenerator = IdentifierGeneratorFactory.create("assigned", type, params, d);
      defaultGenerator = IdentifierGeneratorFactory.create("increment", type, params, d);          
   }
}

要将其用于类,您可以像这样更新Hibernate映射文件:

        <id
        name="Id"
        type="integer"
        column="id"
    >
        <generator class="com.mypackage.FlexibleIDGenerator"/>
    </id>

另一个细节:我向我的基础对象添加了一个名为“GetOverriddenID()”的方法,以避免混淆我是否' m 使用“正常”ID(在 Update() 调用中)或覆盖的 ID。

希望有帮助。

Given that you cannot change the legacy code, Ryan has the right idea. I had to do basically the same thing some time ago in a personal project. There were two parts: the easy part is to allow the effective setting of an otherwise-autonumber-ed column's ID...and the other is to make the ID generator stop overwriting that value when you go to Save().

Here's the code to the FlexibleIDGenerator I used:

public class FlexibleIDGenerator extends IdentityGenerator implements Configurable {
   public static final String DEFAULT = "default";

   private IdentifierGenerator assignedGenerator;
   private IdentifierGenerator defaultGenerator;

@SuppressWarnings("unchecked")
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
      //boolean useDefault = false;

      if (object instanceof OverridableIdentity) {
          if (((OverridableIdentity) object).isIDOverridden()) {
              try {
                  Class cl = object.getClass().getSuperclass();
                  Method[] methods = cl.getDeclaredMethods();

                  for (int i = 0; i < methods.length; i++) {
                      if (methods[i].getName().equalsIgnoreCase("setId")) {
                          methods[i].invoke(object, Integer.valueOf((((OverridableIdentity) object).getOverriddenID())));
                      }
                  }
              } catch (Exception ex) {
                  ex.printStackTrace();
              }
              return assignedGenerator.generate(session, object);
          } else {
              return defaultGenerator.generate(session, object);
          }
      } else {
          return defaultGenerator.generate(session, object);
      }
   }

   public void configure(Type type, Properties params, Dialect d) throws MappingException {
      assignedGenerator = IdentifierGeneratorFactory.create("assigned", type, params, d);
      defaultGenerator = IdentifierGeneratorFactory.create("increment", type, params, d);          
   }
}

To use that for a class, you update your Hibernate mapping file like this:

        <id
        name="Id"
        type="integer"
        column="id"
    >
        <generator class="com.mypackage.FlexibleIDGenerator"/>
    </id>

One other detail: I added a method to my base object called "GetOverriddenID()" to avoid confusion about whether I'm using the "normal" ID (in Update() calls) or the overridden ones.

Hope that helps.

蹲在坟头点根烟 2024-12-14 17:48:31

鉴于您无法更改行的删除,另一种方法是编写您自己的 id 生成器,该生成器仅在尚未分配值的情况下才会获取新的序列值。请参阅 参考指南中的第 5.1.2.2 节了解有关编写自己的生成器的信息。我以前从未尝试过,所以我只能为您指出大致方向。

Given that you can't change the deleting of the rows, another way would be to write your own id generator that will only get a new sequence value if a value isn't already assigned. See the end of section 5.1.2.2 in the reference guide for info about writing your own generator. I've never tried this before, so I can only point you in the general direction.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文