开发者

Hibernate EntityManager.merge() results in the creation of a new entity instead of updating existing one

i have the following (partial) hierarchy:

@MappedSuperclass
public abstract class PersistentEntity {
    @Id
    @GeneratedValue(generator="system-uuid")
    @Type(type开发者_如何学Go = "pg-uuid")
    public UUID getId() {
        return id;
    }
}

@Entity @Inheritance(strategy = InheritanceType.JOINED) @DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING) public abstract class AbstractCredential extends PersistentEntity { //content }

@Entity @DiscriminatorValue("Standard") @PrimaryKeyJoinColumn(name = "ID") public class StandardCredential extends AbstractCredential { //hashcode and quals here, by full data }

AbstractCredential is an entity instead of a @MappedSuperclass so i can select from it by id and get the relevant "concrete" class. my problem is that if i create a new (detached) instance with the id of an existing instance, and then pass that detached instance to merge, hibernate creates a new entity (meaning it generates a new id, and overrides the id field in my newly created instance). to my understanding, hibernate should have overridden all fields in the existing instance with the values in my detached instance.

what am i doing wrong ?


Could be wrong, but I think detached and new are two different states in an entitys' lifecycle. Detached entity has been loaded from database in a session, but the session has been closed. However, in such case Hibernate should be aware that the entity already exists in the database and update the values accordingly, when the entity is later merged. Same will not happen with entities created using keyword new, even if the @Id-value is the same.

This diagram shows it clearly, that an entity in New/Transient-state is different from Detached (JPA). Here's Hibernate (3.5) manual entry for entity states. I also checked from "Java Persistence with JPA"- and "Spring persistence with Hibernate"-books, both explain the entity states and the transitions similarly (detached entity must be persisted to/fetched from database and then detached from the persistence context/session to become detached). Unfortunately, I couldn't find any mentions how the merging should act in a case where you create a new object via new and assign an id to it manually, which leads me to believe that merge isn't supposed to be used this way. Still, could be wrong.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜