我偶然发现merge
了EntityManager
.
我有这门课
@Entity
public class QuestionList {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToOne
private UserEntity user;
@OneToMany(cascade = CascadeType.ALL)
private List<QuestionUnit> units = new ArrayList<QuestionUnit>();
public List<QuestionUnit> getUnits() {
return units;
}
public void setUnits(List<QuestionUnit> units) {
this.units = units;
}
public Long getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addQuestionUnit(QuestionUnit QuestionUnit) {
this.units.add(QuestionUnit);
}
public void setUser(UserEntity user) {
this.user = user;
}
public UserEntity getUser() {
return this.user;
}
}
现在,如果我只是修改合并中units
的一个对象就可以了,但是如果我删除或添加新对象到集合中,合并发生的方式是我得到delete
from
QuestionList_QuestionUnit
where
QuestionList_id=?
然后每一行被一一添加insert
into
QuestionList_QuestionUnit
(QuestionList_id, units_id)
values
(?, ?)
我想知道,是否可以告诉 JPA/Hibernate 只添加/删除与添加/删除的对象关联的行?还是合并仅适用于集合的方式,在我的情况下,我需要编写自己的查询来更新数据库。
我之所以问,是因为这个集合可能非常庞大,并且仅删除所有行并再次插入几乎所有行似乎并不是更新表的好方法。
编辑:根据要求:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class QuestionUnit {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private long id;
@OneToOne(cascade = CascadeType.ALL)
private AnswerUnit correctAnswer;
public QuestionUnit(AnswerUnit correctAnswer) {
this.correctAnswer = correctAnswer;
}
public void setCorrectAnswer(AnswerUnit correctAnswer) {
this.correctAnswer = correctAnswer;
}
public AnswerUnit getCorrectAnswer() {
return this.correctAnswer;
}
public long getId() {
return id;
}
public void setId(long id){
this.id=id;
}
public abstract Object getQuestionContent();
public abstract String getTitle();
}
此层次结构中有 3 个具体类,例如
@Question("openQuestion")
@Entity
public class OpenQuestion extends QuestionUnit {
public void setQuestionContent(String questionContent) {
this.questionContent = questionContent;
}
private String questionContent;
public OpenQuestion() {
this(null, new OpenQuestionAnswer());
}
public OpenQuestion(String questionContent, AnswerUnit correctAnswer) {
super(correctAnswer);
this.questionContent = questionContent;
}
public String getQuestionContent() {
return this.questionContent;
}
public String getTitle() {
return questionContent;
}
}
@Transactional(propagation = Propagation.REQUIRED)
public void update(QuestionList questionList) {
entityManager.merge(questionList);
}
此方法用于所有更新,因为列表处于分离状态。