简体   繁体   中英

How to allow duplicates in an arrayList when using JPA?

I keep getting "java.lang.IllegalStateException: Multiple representations of the same entity" even though I have the @Id set as true and I'm using a one to many relation on my variable.

Here are the classes which I'm trying to relate to one another:

@Entity
@Table(name = "map_area")
public class MapArea extends BasicModel {
   @Id
   @Column(nullable = false, unique = true)
   private String name;

   @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
   @JoinColumn(name = "area", referencedColumnName = "name")
   public List<AlternativeAreaName> alternativeNames;

    public MapArea() {}

    public MapArea(String name) {
        this.name = name;
        this.alternativeNames = new ArrayList<>();
    }

}
@Entity
@Table(name = "alternative_area_name")
public class AlternativeAreaName implements Serializable {

    @Id
    @Column(nullable = false, unique = false)
    private String area;

    @Column(nullable = true)
    private String alternativeName;

    public AlternativeAreaName(){}

    public AlternativeAreaName(String area, String alternativeName) {
        this.area = area;
        this.alternativeName = alternativeName;
    }

}

I want to have JPA create another table that relates to this one simple based on the name variable but whenever I try to add to the list and save to the DB I get

java.lang.IllegalStateException: Multiple representations of the same entity

MapArea mapArea = new MapArea("example");
AlternativeAreaName altAreaName1 = new AlternativeAreaName("example", "alt example");
AlternativeAreaName altAreaName2 = new AlternativeAreaName("example", "alt example2");
mapArea.alternativeNames.add(altAreaName2);

mapAreaRepository.save(mapArea);

You have used the private String area field as the primary key for entity AlternativeAreaName. So when you are trying to add

AlternativeAreaName altAreaName1 = new AlternativeAreaName("example", "alt example");
AlternativeAreaName altAreaName2 = new AlternativeAreaName("example", "alt example2");

Both of them have the same primary key. So it is throwing the above exception.

To generate the primary key for JPA entity, please check

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