Search code examples
mysqlhibernatespring-bootforeign-keysunique-constraint

Spring JPA OneToMany Duplicate Entry MySQLConstraint Violation Error


I have 3 simple Entity ( User, Pizza, Order ).

I want a Order entity that link an user with a list of pizzas, but i have an "Duplicate Entry" error ( MySQLIntegrityConstraintViolationException ):

2018-05-01 21:10:12.145 DEBUG 3493 --- [nio-8080-exec-9] org.hibernate.SQL                        : select next_val as id_val from hibernate_sequence for update
2018-05-01 21:10:12.146 DEBUG 3493 --- [nio-8080-exec-9] org.hibernate.SQL                        : update hibernate_sequence set next_val= ? where next_val=?
2018-05-01 21:10:12.153 DEBUG 3493 --- [nio-8080-exec-9] org.hibernate.SQL                        : insert into comanda (user_id, id) values (?, ?)
2018-05-01 21:10:12.153 DEBUG 3493 --- [nio-8080-exec-9] org.hibernate.SQL                        : insert into comanda_pizza (order_id, pizza_id) values (?, ?)
2018-05-01 21:10:12.154  WARN 3493 --- [nio-8080-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1062, SQLState: 23000
2018-05-01 21:10:12.154 ERROR 3493 --- [nio-8080-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry '3' for key 'UK_ky8uvcbwqkhj6w5t0l7ol1t96'
...
2018-05-01 21:10:12.158 ERROR 3493 --- [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_ky8uvcbwqkhj6w5t0l7ol1t96]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '3' for key 'UK_ky8uvcbwqkhj6w5t0l7ol1t96'

This is User Entity

@Data
@Entity
@Table(name = "profile")
public class User implements Serializable {

    private static final long serialVersionUID = 201804302205L;

    @Id
    @GeneratedValue( strategy = GenerationType.SEQUENCE )
    private Long id;

    @Column(nullable = false)
    private String name;
}

This is Pizza Entity

@Data
@Entity
@Table(name = "pizza")
public class Pizza implements Serializable {

    private static final long serialVersionUID = 201804302204L;

    @Id
    @GeneratedValue( strategy = GenerationType.SEQUENCE )
    private Long id;

    @Column(nullable = false)
    private String name;
}

This is Order Entity

@Data
@Entity
@Table(name = "comanda")
public class Order implements Serializable {

    private static final long serialVersionUID = 201804302206L;

    @Id
    @GeneratedValue( strategy = GenerationType.SEQUENCE )
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Pizza> pizza;

    @ManyToOne
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    private User customer;

    public Order(List<Pizza> pizzas) {
        pizza = pizzas;
    }
}

and this is the OrderService

public Order newOrder(Long userId, List<Long> pizzaIds) {

        Order order = new Order(new LinkedList<Pizza>());

        User user = userservice.getUserById(userId);
        order.setCustomer( user );

        for( Long p: pizzaIds ) {
            Pizza pizza = pizzaservice.getPizzaById(p);
            order.getPizza().add(pizza);
        }

        return repo.save(order);    // <--------- ERROR
}

How can i fix this problem???


Solution

  • My fault!!! I had to write this

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
        name = "comanda_pizza",
        joinColumns = { @JoinColumn(name = "user_id") },
        inverseJoinColumns = { @JoinColumn(name = "pizza_id") }
    )
    private List<Pizza> pizza;
    

    i wrote a @OneToMay