Spring JPA OneToMany重复条目MySQLConstraint违规错误

时间:2018-05-01 19:44:10

标签: mysql hibernate spring-boot foreign-keys unique-constraint

我有3个简单的实体(用户,比萨,订单)。

我想要一个将用户链接到比萨列表的订单实体,但我有一个"重复条目"错误(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'

这是用户实体

@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;
}

这是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;
}

这是订单实体

@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;
    }
}

这是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
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

代码看起来很好。

您很可能没有在@Transactional方法或newOrder课程中添加OrderService

答案 1 :(得分:0)

我的错!!! 我不得不写这个

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