I have two entities: Dog
and Toy
. A Toy
is associated with a String
path.
toys_paths table:
dog_id
toy_path
toy_id
The (dog_id
and toy_id
) should be a unique pair.
Inside Dog
entities it’s stored as Map<Toy, String>
:
@Entity(name = "dogs")
public class Dog {
@Id
@SequenceGenerator(name = "dog_sequence",
sequenceName = "dog_sequence",
allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "dog_sequence")
private Long id;
@ElementCollection
@CollectionTable(name = "toy_paths",
joinColumns = {@JoinColumn(name = "dog_id")})
@MapKeyJoinColumn(name = "toy_id")
@Column(name = "path")
private Map<Toy, String> toyPaths;
}
@Entity(name = "toys")
publi class Toy {
@Id
@SequenceGenerator(name = "toy_sequence",
sequenceName = "toy_sequence",
allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "toy_sequence")
private Long id;
...
Inside DogService
:
public boolean createDog(DogDto dogDto) {
...
Toy toy = toyRepository.findByName("A");
dog.getToyPaths().put(toy, "/some/path"); // if this is removed, no exception
Dog dog = copyData(dogDto);
dogRepository.save(dog); // exception here
return true;
}
When I try to create a new Dog
, I get the exception
org.postgresql.util.PSQLException: ERROR:
duplicate key value violates
unique constraint "toy_paths_pkey"
Detail: Key (dog_id, toy_id)=(67, 2)
already exists.
It only happens when it tries to persist the Map<Toy, String>
. If that map is empty, the Dog
is saved in the database without errors.
What could be causing this exception? The same code used to work fine, but somehow how this is happening.
You need to sign in to view this answers