Home JPA - One to many - duplicate key value error
Reply: 0

JPA - One to many - duplicate key value error

user1862 Published in July 16, 2018, 6:13 pm

I need implement join table for users which will have 2 columns USER_CONTACTS(user_id, contact_id)

I need store for contacts lists for users. I need to make possible that user with id 1 can have in contacts user with id 5, but user 5 can also have in contacts user with id 1 (but he musn't).

I need to be possible do following inserts:

INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(1, 5);
INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(5, 1);

Now I got this error:

Unsuccessful: INSERT INTO USERS_CONTACTS(user_id, contact_id) VALUES(2, 3) 2017-12-05 15:00:15.146 ERROR 14268 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : ERROR: duplicate key value violates unique constraint "uk_j9ggomsdbjte1eqfo5e61vh8a"

Here is my relationship implementation of User in JPA:

public class User{
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", columnDefinition = "serial")
    private long id;

    @JoinTable(name = "USERS_CONTACTS",
            joinColumns = @JoinColumn(name = "USER_ID"),
            inverseJoinColumns = @JoinColumn(name = "CONTACT_ID"))
    private List<User> contacts;

   // ...

Can you tell me how to fix it? I am using Postgre 9.5. Thanks.


For hibernate I have these properties:

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.319555 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO