我创建了多对多关系:
@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;
产品:
@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;
和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)
)
当我插入包含所有不同产品的订单时,一切正常,但当我想在一个订单中添加两个相同的产品时,执行代码时出错:
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();
}
错误:
org.hibernate.NonUniqueObjectException:具有相同标识符值的另一个对象已与会话关联:[org.training.ytaranau.model.Product#1]
可能是什么原因?
答案 0 :(得分:0)
请检查您提供的uniq ID或插入产品实体。它与产品的ID相同。
答案 1 :(得分:0)
如前所述,你通过两次添加相同的objcet来制动关系的独特性。
因此,作为解决方案,您可以创建一个像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;
}