简体   繁体   中英

grails create criteria non unique object error if wrapped in withNewSession

I have criteria that looks like this

  //Inventory.withNewSession{
    Set inventory=Inventory.withCriteria{
       setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
       inventoryDetail{
           eq('userAdded',true)
       }
       ...
     }
//}

If I wrap that in a withNewSession I get duplicate key and non unique object in the session errors. If I don't use withNewSession, it works.

Why?

If you already had a session and loaded object with id=1 (eg), and then created a new session and loaded that same object. When the new session block ends, the hibernate session joins the existing session (am I saying this right?) and now you have your both objects loaded with the same ID.

I'm not sure why you're using withNewSession here, is there a path that this may execute without a hibernate session? Are you trying, as TDC suggests, to isolate this transactionally?

maybe try to use replace withNewSession with withTransaction?

Inventory.withTransaction{
    Set inventory=Inventory.withCriteria{
       setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
       inventoryDetail{
           eq('userAdded',true)
       }
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM