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?