当前位置: 首页 > 知识库问答 >
问题:

ManyToMany关系:在刷新之前保存瞬态实例

常波
2023-03-14

将数据保存到数据库时,我收到异常 org.hibernate.TransientObjectException:对象引用未保存的瞬态实例 - 在刷新之前保存瞬态实例:com.example.api.entity.Product

我有两个实体。

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

}

我阅读了这个ex的内容,并试图将Casca eType更改为另一个,但没有帮助。

共有1个答案

柴耀
2023-03-14

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

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

 类似资料: