views:

92

answers:

2

Hi all, i have an entity that contains two other entities with @ManyToOne relationship.

@Entity
public class A extends Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @Cascade(CascadeType.SAVE_UPDATE)
    private B b;

    @ManyToOne
    @Cascade(CascadeType.SAVE_UPDATE)
    private C c;

}

If i try to save an A instance that have "B_ID" and "C_ID" of another A record i get the exception:

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

For example:

A table
|   ID  |   B_ID    |   C_ID    |
|    1  |      1    |   null    |    // this works
|    2  |   null    |      1    |    // this works
|    3  |      1    |      x    |    // this throws the exception
|    4  |      x    |      1    |    // this throws the exception

x=any value of existent B/C_ID 

B_ID and C_ID are not unique in my model and (B_ID + C_ID) is not an unique constraint!!

What can i do?

Thank in advance.

+2  A: 

Hibernate is not complaining about database uniqueness here, it's complaining that the current Session already contains an object with the same ID as a new object that you're trying to save. It won't permit this - Hibernate has a strict requirement that a given ID cannot be represented by two different objects in the scope of a single session.

At some point, your application has save dor loaded an entity with that same ID, and that object is already "registered" with the session. It's hard to tell in this specific case which ID it's complaining about, since the exception text isn't clear. Try temporarily removing the cascade directives and see if it still happens, try to it narrow down.

If necessary, you can force the session to "forget" about any existing objects for a given ID (using Session.evict() in the Hibernate API, or EntityManager.detach() in the JPA 2.0 API), but that's not a very elegant solution.

To reiterate - this exception has nothing at all to do with the database constraints, it's about Hibernate protecting the consistency of its internal in-memory state.

skaffman
Thanks, the only things i i load from db are B and C, and i use them in A object. But B and C have CascadeType.SAVE_UPDATE, so they are not saved again, but only update... i hope...
blow
The problems comes out at start too, when session is new.
blow
@skaffman: removing the cascade directives works good, but... WHY???Without "Cascade.SAVE_UPDATE" hibernate should try to re-SAVE "A" and "B" that are already presents in db and so throw an exception, but it works instead... why?
blow
A: 

now I encountered this problem, are you have resolved it?

Not yet im sorry
blow