我使用的是Spring Boot 2.3.0。
我一边是ManyToOne关系,另一边是OneToMany关系。一个父代对应多个子代,但多个子代对应一个父代。我正在尝试在不影响父级的情况下删除子级。我在父字段的子字段中设置了nullable = false,因为我不想在parent_to_child表中意外地为父字段设置空值。我希望这样的事情被强制执行并被抓住。
当我在从Reader对象(这是父对象)的List<TBRList>中删除一个TBRList项(这是子项)后执行readerRepository.save(reader)时,我一直收到一个错误,说明在尝试删除子项时父字段不能为空。如果我在子对象的父字段上将nullable设置为false,那么我的父对象就会消失。
我以为我知道这是怎么回事,但显然不是。
我有:
@Entity //parent
public class Reader implements Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@JsonIgnore
private Long id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "reader", orphanRemoval = true)
Set<TBRList> tbrLists = new HashSet<>();
//other fields, getters, setters, etc.
}
@Entity(name = "tbr") //child
public class TBRList implements Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "reader_id", nullable = false)
private Reader reader;
//other fields, getters, setters, etc
}在下面的代码片段中,readerRepository.save(reader)是发生org.hibernate.PropertyValueException: not-null property references a null or transient value : com.me.project.entity.TBRList.reader异常的地方。
if (reader.hasTBRList(tbrListName)) {
Iterator<TBRList> it = reader.getTbrLists().iterator();
while (it.hasNext()) {
TBRList tbrList = it.next();
if (tbrList.getName().equals(tbrListName)) {
it.remove();
readerRepository.save(reader);
break;
}
}
}我还尝试在TBRList中将reader设置为null,并通过tbrListRepository对其执行delete操作,但同样的事情也发生了。事实上,我已经尝试了太多的东西来记住所有的东西(我试着在几个小时的搜索和尝试之后提出问题作为最后的结果)。
如果我不希望Child.parent为null,并且希望能够在不删除父级的情况下从父级中删除子级,那么我在尝试建立父级/子级关系时做错了什么?
发布于 2020-07-09 05:12:45
我创建了相同的类,并按照您的要求执行以下结果:
@Entity(name = "tbr")
@Data
public class TBRList {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@JsonIgnore
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "reader_id", nullable = false)
private Reader reader;
}
@Entity
@Data
public class Reader {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private Long id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "reader", orphanRemoval = true)
Collection<TBRList> tbrLists ;
}https://stackoverflow.com/questions/62803434
复制相似问题