错误:org.hibernate.PersistentObjectException:分离的实体传递给持久化

时间:2018-10-27 17:34:30

标签: java mysql reactjs spring-boot

我正在研究Spring-boot + ReactJs应用程序。我基本上有两个实体(品牌和家庭),它们之间存在一对多的关系。

@Entity
@Table(name = "brands")
public class Brand extends UserDateAudit {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    @Size(max = 140)
    private String name;

    @Lob @JsonProperty("image")
    private byte[] image;

    @OneToMany
    private Set<Family> family;

@Entity
@Table(name = "family")
public class Family extends UserDateAudit {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;

        @NotBlank
        @Size(max = 140)
        private String name;

        @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
        @ManyToOne(fetch = FetchType.LAZY,cascade=CascadeType.ALL, optional = false)
        @JoinColumn(name = "brand_id")
        private Brand brand;

当我创建“家庭”对象时,它会引发以下错误。

org.hibernate.PersistentObjectException: detached entity passed to persist: com.example.polls.model.Brand
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:807) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:774) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]

createFamily()如下。

public Family createFamily(@Valid FamilyRequest familyRequest) {
            Family family = new Family();
            family.setName(familyRequest.getName());
            family.setBrand(familyRequest.getBrand());
            return familyRepository.save(family);
        }

通过调试,我发现'familyRequest'同时具有'name'和'Brand_id'

ReactJS:

 handleSubmit(event) {
        event.preventDefault();
      //  console.log('image: '+this.state.brand_id.text);
        const familyData = {
            name: this.state.name.text,
            brand: {id : this.state.brand_id.text}
        //    band_id: this.state.band_id
        };

        createFamily(familyData)
        .then(response => {
            this.props.history.push("/");
        }).catch(error => {
            if(error.status === 401) {
                this.props.handleLogout('/login', 'error', 'You have been logged out. Please login create family.');
            } else {
                notification.error({
                    message: 'Polling App',
                    description: error.message || 'Sorry! Something went wrong. Please try again!'
                });
            }
        });
    }

我不确定我为brand_id设置的值是否正确。 请帮我解决这个问题。

1 个答案:

答案 0 :(得分:3)

您的映射不正确。 a bidirectional OneToMany的一侧必须使用mappingBy属性。

将所有操作层叠在ManyToOne上没有任何意义:创建家族时,您不想创建品牌:它已经存在。而且,当您删除一个家庭时,您不想删除其品牌,因为许多其他家庭都引用了该品牌。