我现在用hibernate,想对一个有联合主键的表的某个字段进行更新,结果给我报异常:org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.persistent.Consumpatch#com.persistent.ConsumpatchId@68fd7db3]
我在线等!我的方法如下:
public boolean updateGroup(int typeid,int producterid,int specid,String branchid){
Session session=HibernateSessionFactory.currentSession();
Transaction tx=session.beginTransaction();
try{
ConsumpatchId conid=new ConsumpatchId();
conid.setTypeid(typeid);
conid.setSpecificid(specid);
conid.setBranchid(branchid);
conid.setConmpatchid(conid.getConmpatchid()+1);
Consumpatch cons=(Consumpatch)session.load(Consumpatch.class,conid);
cons.setProducerid(producterid);
session.saveOrUpdate(cons);
session.flush();
tx.commit();
}catch(HibernateException he){
if(tx!=null)
tx.rollback();
he.printStackTrace();
return false;
}finally{
session.close();
}
return true;
}

解决方案 »

  1.   

    ID已经存在啊,你模似题一下啊public   boolean   updateGroup(int   typeid,int   producterid,int   specid,String   branchid){ 
    Session   session=HibernateSessionFactory.currentSession(); 
    Transaction   tx=session.beginTransaction(); 
    try{ 
    ConsumpatchId   conid=new   ConsumpatchId(); conid.setTypeid(typeid); 
    conid.setSpecificid(specid); 
    conid.setBranchid(branchid); 
    conid.setConmpatchid(conid.getConmpatchid()+1); 
    Consumpatch   cons=(Consumpatch)session.load(Consumpatch.class,conid); 
    cons.setProducerid(producterid); 
    session.saveOrUpdate(cons); 
    session.flush(); 
    tx.commit(); 
    }catch(HibernateException   he){ 
    if(tx!=null) 
    tx.rollback(); 
    he.printStackTrace(); 
    return   false; 
    }finally{ 
    session.close(); 

    return   true; 
    }
      

  2.   

    楼主,你确定在你的数据库中有符合要求的记录吗?从你的异常信息来看,是你的数据库中没有符合要求的记录。
    在按主键查询而没有找到对应的记录时,程序将出现ObjectNotFoundException——这是load()方法的特点之一。顺便提个建议:
    把load()换成get()吧。get()的特点是在没找到对应记录时返回null,而不会抛异常。所以,解决方案为:
    1、确定你的数据库中存在符合要求的记录
    2、把load()换成get()
      

  3.   

    [接3楼]
    突然又发现更严重的问题:楼主的代码有点不合逻辑。
    如果你之前能够成功load(),说明记录是必然存在的。那么肯定是update了,何必又使用saveOrUpdate()?saveOrUpdate()内部还会按主键去查一次的,楼主你把自己陷入泥潭了……如果你想saveOrUpdate(),说明你要插的记录可能存在也可能不存在,那之前的查询不但没有意义,而且必定带来异常:如果用load(),在记录不存在时将ObjectNotFoundException。如果使用get(),在记录不存在时返回null,则接下来会NullPointerException所以,解决方案之补充:
    如果你是想saveOrUpdate(),那就应该把之前的查询去掉,直接new Consumpatch()并对其属性赋值,然后saveOrUpdate()。
      

  4.   

    ConsumpatchId   conid=new   ConsumpatchId(); 
    conid.setTypeid(typeid); 
    conid.setSpecificid(specid); 
    conid.setBranchid(branchid); 
    conid.setConmpatchid(conid.getConmpatchid()+1); 
    楼主代码很有问题。先实例化一个conid,这时候是个空对象,conid.getConmpatchid(),这个方法你要不是空,要不就是0。想想你每次到这都取到什么,不行就直接用find不用load