Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem saveOrUpdate object Hibernate (a different object with the same identifier session) [duplicate]

Possible Duplicate:
Hibernate: different object with the same identifier value was already associated with the session

I have problem when want update my object to database using hibernate when I want update(branchDao.update(be); ) it's throw below exception

a different object with the same identifier value was already associated with the session

this my code:

            LoginEntity le = loginDao.getSpecificLogin(pkId);
            le.setPassword(password);
            le.setRoles(role);
            loginDao.update(le);               
            HumanEntity he = humanDao.getHumanById(humanID);  // humanEntuty farde morede nazar ro bar hasbe Email taraf load mikonad
            he.setHumanEmail(oemail);
            he.setHumanFamily(olname);
            he.setHumanName(ofname);
            humanDao.update(he);
            superBranchUsername = branch.getFatherUsername();
            int superBranchId = branchDao.getBranchIdByUserName(superBranchUsername);
            BranchEntity superBranch = branchDao.load(superBranchId);
            BranchEntity be = new BranchEntity();
            setBranchEntity(be, he, pkId, bname, confirmed, level, studentCount, uname, superBranch, le);
            branchDao.update(be); //this line throw exception

and for update :

 public void update(T transientObject) throws DatabaseException {
        Session s = HibernateUtil.getSession();
        Transaction tx = null;
        try {
            tx = s.beginTransaction();
            s.update(transientObject);
            s.flush();
            tx.commit();
        } catch (HibernateException e) {
            System.out.println(e.getMessage());
            tx.rollback();
            e.printStackTrace();

            throw new DatabaseException("cant't update object");
        }
    }

and this my BranchEntity class

@Entity
@Table(name = "branch", uniqueConstraints = {@UniqueConstraint(columnNames = {"bname", "branch_fk"})})
public class BranchEntity implements Serializable {

    @Id
    @GeneratedValue
    private int id;
    @Column(name = "username", length = 64, nullable = false)
    private String userName;
    @Column(name = "bname", length = 64)
    private String branchName;
    @Column(name = "studcount")
    private int studCount;
    @Column(name = "blevel", columnDefinition = "int default 0")
    private int level;
    @Column(name = "confirmed", columnDefinition = "tinyint default 0")
    private int confirmed;
    @OneToMany(mappedBy = "branch", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    private Set<BranchBuildingEntity> branchbuilding = new HashSet<BranchBuildingEntity>();
    @OneToMany(mappedBy = "branch", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    private Set<BranchPictureEntity> branchPicture = new HashSet<BranchPictureEntity>();
    @OneToOne(fetch = FetchType.EAGER)    
    @JoinColumn(name = "login_fk", nullable = true)
    private LoginEntity login;
    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "human_fk", nullable = true)
    private HumanEntity human;        
    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "branch_fk", referencedColumnName = "id", nullable = true)
    private BranchEntity superBranch;

Some where I read that problem because I use @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) but what shoud I do when I need cascade?

like image 275
Am1rr3zA Avatar asked Jul 28 '09 08:07

Am1rr3zA


People also ask

What does session saveOrUpdate () method do?

The Session. save() method does an INSERT to store the object into the database and return the identifier generated by the database. On the other hand, saveOrUpdate() can do INSERT or UPDATE depending upon whether object exists in database or not.

What is the difference between the Save () and saveOrUpdate () method of hibernate?

Difference between save and saveOrUpdate in Hibernate The main difference between save and saveOrUpdate method is that save() generates a new identifier and INSERT record into the database while saveOrUpdate can either INSERT or UPDATE based upon the existence of a record.

What is session merge () method in hibernate?

So the merge method does exactly that: finds an entity instance by id taken from the passed object (either an existing entity instance from the persistence context is retrieved, or a new instance loaded from the database) copies fields from the passed object to this instance. returns a newly updated instance.

What does session merge do?

Session. merge() is used each time an object is retrieved from the cache to create a local copy of it in each Session which requests it. The cached object remains detached; only its state is moved into copies of itself that are local to individual Session objects.


1 Answers

org.hibernate.Session.update() is not for transient objects - it's for updating persistent objects. The message you quote "a different object with the same identifier value was already associated with the session" explains the problem. You create a brand new object

BranchEntity be = new BranchEntity();

fill its fields and pass it to update. But update expects an object that is associated with the session. So you should load the object using your dao, something like

BranchEntity be = branchDao.loadBranchEntity(...);
like image 94
Tadeusz Kopec for Ukraine Avatar answered Oct 18 '22 06:10

Tadeusz Kopec for Ukraine