Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

jpa

Searched through SO but looks like there is no similar case to mine.

There is an entity Country, with a single field:

public class Country {

    @Id
    @Column(name = "COUNTRY_CODE")
    private String countryCode;

    public boolean equals(Object o) {}

    public int hashCode() { }
}

And another class which has a collection of these entries:

public class Product {

    @ManyToOne(fetch = EAGER, cascade = ALL)
    @JoinColumn(name = "COUNTRY_CODE")
    private Country country;
}

When setting country through:

product.setCountry(new Country("lv"))

I assume that it will just be saved, if it is present.

But instead I get an exception - a different object with the same identifier value was already associated with the session

like image 237
sandris Avatar asked Aug 09 '16 14:08

sandris


1 Answers

By seeing as much code you have provided this types of problem comes because the objects are not referring to the same Java object instance.This can happen when you have used same session object for read & write Or if you are putting same object in single session. They are referring to the same row in the database (i.e. the same primary key) but they're different copies of it.So what is happening is that the session, which is managing the entities would be keeping track of which Java object corresponds to the row with the same primary key.

I would recommend you to try below given code.

1- Just set cascade to MERGE, that should work for you.

       OR

2- @GeneratedValue(strategy = GenerationType.SEQUENCE)   OR Other GenerationType 
like image 159
Gokul Avatar answered Nov 07 '22 12:11

Gokul