【问题标题】:ManyToMany relation: save the transient instance before flushing多对多关系:在刷新之前保存瞬态实例
【发布时间】:2019-07-29 08:55:31
【问题描述】:

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

我有两个实体。

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 更改为另一个,但没有帮助。

【问题讨论】:

  • 你能告诉我保存方法吗!!

标签: java json spring hibernate


【解决方案1】:

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

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

【讨论】:

  • 谢谢,去掉ElementCollection注解后就可以了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 2012-11-08
  • 2015-09-27
  • 2021-03-03
相关资源
最近更新 更多