简体   繁体   English

Hibernate NonUniqueObjectException多对多

[英]Hibernate NonUniqueObjectException many-to-many

I've created many-to-many relationships: 我已经建立了多对多关系:

@Entity
@Table(name = "Orders")
public class Order {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@NotNull
@Column(name = "Id", unique = true)
private int id;

@ManyToOne
@JoinColumn(name = "UserId")
private User user;

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "order_products", joinColumns = {@JoinColumn(name = "Order_id")},
        inverseJoinColumns = {@JoinColumn(name = "Product_id")})
private List<Product> products;

Products: 产品:

@Entity
@Table(name = "products")
public class Product {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@NotNull
@Column(name = "Id", unique = true)
private int id;


@NotNull
@Size(min = 5, max = 30)
@Column(name = "Name")
private String name;


@NotNull
@Column(name = "Price")
private double price;

@ManyToMany(fetch = FetchType.EAGER, mappedBy = "products")
private List<Order> orders;

and sql code; 和sql代码;

CREATE TABLE IF NOT EXISTS products (
  Id    INT PRIMARY KEY AUTO_INCREMENT,
  Name  VARCHAR(30) UNIQUE NOT NULL,
  Price DOUBLE             NOT NULL
);
CREATE TABLE IF NOT EXISTS orders (
  Id     INT PRIMARY KEY AUTO_INCREMENT,
  UserId INT,
  FOREIGN KEY (UserId) REFERENCES users (Id)
);
CREATE TABLE IF NOT EXISTS order_products (
  Order_id   INT,
  Product_id INT,
  FOREIGN KEY (Order_id) REFERENCES orders (Id),
  FOREIGN KEY (Product_id) REFERENCES products (Id)
)

When I insert an order with all different products, all works, but when I want to add in one order two same products, I have an error when executing code: 当我插入具有所有不同产品的订单时,所有产品都可以使用,但是当我要在一个订单中添加两个相同产品时,执行代码时出现错误:

Session session = sessionFactory.openSession();
try {
    session.beginTransaction();
    session.save(order);
    session.getTransaction().commit();
    session.close();
} catch (RuntimeException e) {
    session.getTransaction().rollback();
    session.close();
    e.printStackTrace();
}

Error: 错误:

org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [org.training.ytaranau.model.Product#1] org.hibernate.NonUniqueObjectException:具有相同标识符值的另一个对象已与会话相关联:[org.training.ytaranau.model.Product#1]

What can be the reason? 可能是什么原因?

Please check the uniq id that you provide or insert to Product Entity. 请检查您提供或插入到产品实体的uniq ID。 it was the same id of product. 它是产品的相同ID。

As mentioned before are you braking the uniqeness of the relation by adding the same objcet twice. 如前所述,您通过两次添加相同的对象来制动关系的唯一性。

So as a solution you can make an association object like ProductOrder and add a quantity field. 因此,作为解决方案,您可以制作一个关联对象(如ProductOrder)并添加一个数量字段。

@Entity
public class ProductOrder {
    @Id
    private long orderId;

    @Id
    private long productId;

    private int quantity;

    @ManyToOne
    @PrimaryKeyJoinColumn(name="ORDERID", referencedColumnName="ID")
    private Order order;

    @ManyToOne
    @PrimaryKeyJoinColumn(name="PRODUCTID", referencedColumnName="ID")
    private Product product;
}

Order {
    @OneToMany(mappedBy="order")
    private List<ProductOrder> prodctOrder;
}

Product {
    @OneToMany(mappedBy="product")
    private List<ProductOrder> prodctOrder;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM