休眠Session.save问题 [英] Hibernate Session.save issue

查看:109
本文介绍了休眠Session.save问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我有一个域对象让我们说学生和它的卷不作为主键

这里是它的示例映射。

  @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 ;

$ / code>

问题:让我们说一个特定的学生是否从数据库中删除,然后在重新入场时再次承认我想保留旧版没有。所以当我打电话给session.save时,hibernate会根据指定的Sequence指定一个新的No,而不是通过setRollNo()方法设置。有没有办法在hibernate中实现这一点?

解决方案

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



以下是我使用的FlexibleIDGenerator的代码:

 公共类FlexibleIDGenerator扩展了IdentityGenerator实现可配置{
public static final String DEFAULT =default;

私有IdentifierGenerator assignedGenerator;
私有标识符生成器defaultGenerator;

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

if(object(instance)of OverridableIdentity){
if(((OverridableIdentity)object).isIDOverridden()){
try {
Class cl = object.getClass( ).getSuperclass();
Method [] methods = cl.getDeclaredMethods(); (int i = 0; i< methods.length; i ++){
if(methods [i] .getName()。equalsIgnoreCase(setId)){$ b(

) $ b methods [i] .invoke(object,Integer.valueOf((((OverridableIdentity)object).getOverriddenID())));

$ b} 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()的方法,以避免混淆关于我是否使用正常ID(在Update()调用中)或重写的。



希望有帮助。


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?

解决方案

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.

这篇关于休眠Session.save问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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