我正在开发springboot+js应用程序。基本上,我有2个实体(品牌和家庭)有一对多的关系。
@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;
当我创建“family”对象时,它抛出以下错误。
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\u id”
React:
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!'
});
}
});
}
我不确定我为品牌标识设置的值是否正确。请帮我解决这个问题。
1条答案
按热度按时间92vpleto1#
您的Map不正确。双向onetomany的一侧必须使用mappedby属性。
而将所有的操作级联到一个manytone上是没有意义的:当你创建一个家族时,你不想创建它的品牌:它已经存在了。当您删除一个族时,您不想删除它的品牌,因为它被许多其他族引用。