简体   繁体   中英

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;

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]

What can be the reason?

Please check the uniq id that you provide or insert to Product Entity. it was the same id of product.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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