简体   繁体   中英

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

I have two entities.

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
}

And I have a JSON with data to add.

{
"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.

I think you must remove the ElementCollection annotation. The ManyToMany annotation is enough.

You could try to add the relationship on the Product class too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM