gpt4 book ai didi

java - 多对多关系 : save the transient instance before flushing

转载 作者:行者123 更新时间:2023-12-02 09:39:06 25 4
gpt4 key购买 nike

将数据保存到数据库时,出现异常org.hibernate.TransientObjectException:对象引用未保存的 transient 实例 - 在刷新之前保存 transient 实例:com.example.api.entity。产品展示

我有两个实体。

用户.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
}

产品.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"

}

我读到了有关此异常(exception)的信息,并尝试将 CascadeType 更改为另一个,但没有帮助。

最佳答案

我认为您必须删除 ElementCollection 注释。 ManyToMany 注释就足够了。

您也可以尝试在 Product 类上添加关系

关于java - 多对多关系 : save the transient instance before flushing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57250308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com