java spring jpa - 具有相同标识符值的不同对象已经与会话相关联

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38853317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:50:03  来源:igfitidea点击:

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

javaspringjpa

提问by sandris

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

通过 SO 搜索,但看起来没有与我类似的案例。

There is an entity Country, with a single field:

有一个实体 Country,只有一个字段:

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

但是我得到了一个异常 - 一个具有相同标识符值的不同对象已经与会话相关联

回答by Gokul

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.

通过查看您提供的尽可能多的代码,出现这种类型的问题是因为对象没有引用相同的 Java 对象实例。当您使用相同的会话对象进行读写或者将相同的对象放入单个会话时,就会发生这种情况. 它们指的是数据库中的同一行(即相同的主键),但它们是它的不同副本。所以发生的事情是管理实体的会话将跟踪哪个 Java 对象对应于具有相同主键的行。

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