[英]ManyToMany relation: save the transient instance before flushing
While saving data to DB, I'm getting an exception org.hibernate.TransientObjectException : object references an unsaved transient instance - save the transient instance before flushing: com.example.api.entity.Product 将数据保存到DB时,出现异常org.hibernate.TransientObjectException :对象引用了一个未保存的临时实例-在刷新之前保存该临时实例:com.example.api.entity.Product
I have two entities. 我有两个实体。
User.java User.java
@Entity
@Table(name = "users", schema = "public")
public class User {
@Id
@Column(name = "user_id", updatable = false, nullable = false, unique = true)
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;
@Column(name = "name")
private String name;
@Column(name = "product")
@ElementCollection(targetClass = Product.class)
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "products_users",
joinColumns = {@JoinColumn(name = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "product_id")})
private Set<Product> products;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd@HH:mm:ss")
@Column(name = "created_on")
@JsonIgnore
private Date createdOn;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd@HH:mm:ss")
@Column(name = "modified_on")
@JsonIgnore
private Date modifiedOn;
//getters, setters, contructors
}
Product.java Product.java
@Entity
@Table(name = "product", schema = "public")
public class Product {
@Id
@Column(name = "product_id", updatable = false, nullable = false, unique = true)
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private UUID id;
@Column(name = "name")
private String name;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd@HH:mm:ss")
@Column(name = "created_on")
@JsonIgnore
private Date createdOn;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd@HH:mm:ss")
@Column(name = "modified_on")
@JsonIgnore
private Date modifiedOn;
//getters, setters, contructors
}
And I have a JSON with data to add. 我有一个要添加数据的JSON。
{
"name": "Max",
"products": [{
"name": "product1",
"createdOn": "2019-07-26T11:13:39",
"modifiedOn": "2019-07-26T11:13:39"
}
],
"createdOn": "2019-07-26T11:13:39",
"modifiedOn": "2019-07-26T11:13:39"
} }
I read about this exeption and tried to change CascadeType to another, but it doesn't help. 我阅读了有关此示例的信息,并尝试将CascadeType更改为另一个示例,但这无济于事。
I think you must remove the ElementCollection
annotation. 我认为您必须删除
ElementCollection
批注。 The ManyToMany
annotation is enough. ManyToMany
注释就足够了。
You could try to add the relationship on the Product
class too 您也可以尝试在
Product
类上添加关系
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.