简体   繁体   中英

org.hibernate.PersistentObjectException: detached entity passed to persist while using hashMap to persist objects

I have a class Notification which contains an object messengerData:

public class Notification{

    @OneToOne(mappedBy = "messengerDataId")
    private MessengerData messengerData;
    ...
}

The MessengerData class contains a map of resources, it means that messengerdata contains couples of this is why I am using the one to many relation:

public class MessengerData{

        @OneToOne(mappedBy = "messengerData")
        private Notification notification;

        @OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE },
                 fetch = FetchType.EAGER)
        @Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DETACH })
        @JoinTable(name = HemisTablesNames.MESSENGER_RESOURCES, joinColumns = @JoinColumn(name = "idResource"),
                 inverseJoinColumns = @JoinColumn(name = "messengerDataId"))

        private Map<String, Resource> resources = new HashMap<String, Resource>();
        ...

The class Resource contains a map< String, NotificationTextData>:

    @OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE },
        fetch = FetchType.EAGER)
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DETACH })
@JoinTable(name = HemisTablesNames.MESSENGER_NOTIF_TEXT_DATA, joinColumns = @JoinColumn(name = "idNTD"),
        inverseJoinColumns = @JoinColumn(name = "idResource"))
private Map<String, NotificationTextData> textDatas;

Here is how I save object:

EntityManager.persist(notification);
EntityManager.commitTransaction();

My problem is that I am getting this exception:

Couldn't save notification : org.hibernate.PersistentObjectException: detached entity passed to persist: com.ubiant.hemis.type.Notification

Could someone help me with this?

try to use something like this:

@ElementCollection(targetClass = String.class)
@CollectionTable(name = "MAP")
@MapKeyColumn(name="key")
@Column(name="value")
private Map<String, String> map;

You're trying to persist an object without some references. Maybe that's your problem.

If you instantiate notification then you can't use persist , because the produced object is not attached to hibernate session. You should use merge instead of persist

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