开发者

Hibernate: Update onetomany list

I have got a onetomany relation in Hibernate:

@Entity 
public class Project
    @OneToMany(cascade = CascadeType.ALL)
    @OrderColumn(name = "project_index")
    List<Application> applications;


@Entity
public class Application

Now, I tried to update an application directly:

    session.merge(application);

The result is that a new Application is created, instead of updating the entity. How can I reatach my entity properly and update my entit开发者_如何学运维y?

Thank you


Solution:

@Override
public boolean equals(Object obj)  {
    if (!(obj instanceof Application)) {
        return false; 
    }
    Application app = (Application)obj;

    return id == app.getId();
}

@Override
    public int hashCode () {
        return status.hashCode();
}


When you call session.merge(), it returns an object which is the value of that entity in the context of the current session. You can't simply reuse the existing object in a new session, because the object is outside of its session's life (and a new object to represent the same entity may already have been created in the new session). You need to honor hibernate's single-instance-per-entity-per-session semantics by using the new object in place of the old.

If you find that calling merge() results in a new entity being created (an insert statement is generated on flush), this might mean that the identifier of the object you're trying to merge doesn't match, or there is an issue with your equals() or hashCode() implementation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜