0

I am saving multiple related objects in one transaction one at time and I am looking for away to prevent ConstraintViolationException when I save a child object.

Code would look like this.

try{
    //with given session
    session.getTransaction().begin();
    session.save(objectA);
    objectB.setObjectA(objectA);
    //do something with object B before save
    session.save(objectB);
    if(!objectB.getObjectCSet().isEmpty()){
        for(ObjectC objectC:objectB.getObjectCSet){
             objectC.setObjectB(objectB);
             //do something with object C before saving
            session.save(objectC);
        }
    }
    session.getTransaction().commit();
}catch(Exception e){
    session.getTransaction().rollback();
}finally{
    if(session != null){
        session.flush();
        session.clear();
        session.close();
    }
}

If I am not mistaken I could just use cascade and do something like session.save(objectA); with configuration of cascade="save". I don't know how hibernate handle cascade but I would like to know if it does something similar.

1 Answer 1

1

Assuming there are entity associations between ObjectA to ObjectB and ObjectB to ObjectC, you can use cascade=CascadeType.ALL when you define the entity associations using @OneToMany etc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.