[英]ManyToMany relation: save the transient instance before flushing
将数据保存到DB时,出现异常org.hibernate.TransientObjectException :对象引用了一个未保存的临时实例-在刷新之前保存该临时实例:com.example.api.entity.Product
我有两个实体。
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
@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
}
我有一个要添加数据的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"
}
我阅读了有关此示例的信息,并尝试将CascadeType更改为另一个示例,但这无济于事。
我认为您必须删除ElementCollection
批注。 ManyToMany
注释就足够了。
您也可以尝试在Product
类上添加关系
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.