我在帖子下面列出了4个实体。客户端和产品已经在数据库中。 Orders和OrdersProducts存在问题。我创建了Orders对象,然后我添加了客户端(已经在数据库中)和OrdersProducts的ArrayList,但是我收到了错误:
object references an unsaved transient instance - save the transient instance before flushing: pl.take.server.model.Orders.clients -> pl.take.server.model.Clients
当我不添加客户端时,只有OrderProducts的ArrayList它在数据库中,但OrderProducts没有外键。怎么了?我使用Mysql服务器和hibernate。
@Entity
public class Clients implements Serializable {
@Id
@GeneratedValue
private int idClient;
private String clientName, clientSurname, clientCompany;
@OneToMany(mappedBy = "clients")
private List<Orders> listOfOrders = new ArrayList<Orders>();
}
@Entity
public class Orders implements Serializable {
@Id
@GeneratedValue
private int idOrder;
private double totalAmount;
@ManyToOne
@JoinColumn(name = "idClientFK")
private Clients clients;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "orders")
private List<OrdersProducts> listOfProductsInOrder = new ArrayList<OrdersProducts>();
}
@Entity
public class OrdersProducts implements Serializable {
@Id
@GeneratedValue
private int idOrderProduct;
private int productAmount;
private float productsValue;
@ManyToOne
@JoinColumn(name = "idOrderFK")
private Orders orders;
@ManyToOne
@JoinColumn(name = "idProductFK")
private Products products;
}
@Entity
public class Products implements Serializable {
@Id
@GeneratedValue
private int idProduct;
private String productName;
private double productValuePerUnit;
private String productUnit;
private int productCount;
private String productCompany;
@OneToMany(mappedBy = "products")
private List<OrdersProducts> listOfOrdersProducts = new ArrayList<OrdersProducts>();
}
答案 0 :(得分:1)
您有双向关联订单&lt; - &gt;客户端(双向关联声明为mappedBy
注释属性)。
Hibernate不知道哪个对象是主要对象。
您有两种选择:
@OneToMany
级联。 (@OneToMany(cascade = CascadeType.ALL
)选择第一个选项,你将以这样的结尾: ...
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "idClientFK")
private List<Orders> listOfOrders = new ArrayList<Orders>();
并且保存逻辑将是这样的:
Clients client = new Client();
List<Orders> orders = new ArrayList<>();
orders.add(new Orders());
clients.setOrders(orders);
enityManager.save(clients);
答案 1 :(得分:1)
考虑到您有双向关系,如果您想要保留订单,则必须:
前提条件:SesionScope bean中有一个分离的Client实体,WiewScoped支持bean中有一些分离的Product实体。
在您想要保留订单的商务方法中: