hibernate - 用于条件更新的 JPA 注释
问题描述
我有两个实体
@Entity
@Table(name = "question", uniqueConstraints =
@UniqueConstraint(columnNames = "text"))
public class Question implements Serializable {
@Id
@GeneratedValue
private Long id;
private String text;
@OneToMany(mappedBy = "question", cascade = CascadeType.ALL, orphanRemoval = true, targetEntity = Answer.class)
private Set<Answer> listAnswers = new HashSet<Answer>();
}
@Entity
public class Answer implements Serializable {
@Id
@GeneratedValue
private Long id;
private String text;
private Integer result = 0;
@ManyToOne(targetEntity = Question.class, cascade = CascadeType.MERGE)
@JoinColumn(name = "question_id", nullable = false)
private Question question;
}
当我尝试合并()实体问题时回答覆盖(“hibernate.hbm2ddl.auto”=“update”)中的所有数据:
EntityManagerFactory emf = Persistence.createEntityManagerFactory(
"some.package.settings", properties);
assertTrue(emf.isOpen());
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.merge(question);
if (em.getTransaction().isActive()) {
em.getTransaction().commit();
}
em.close();
emf.close();
在实体中,答案字段结果的值为:0、1、2。如果 Answer.result > 0 ,我需要禁止更新记录。
有没有这样的注释?我看到了@PreUpdate/@PostUpdate 注释。如果需要,可以在更新和恢复之前保存数据,但可能以另一种方式存在?
解决方案
我的程序解析相同的资源并生成带有答案的问题列表。我需要用数据库中的答案检查问题记录。如果存在问题,我只添加了答案。如果问题的答案也存在,我需要更新值 == 0 中的 Answer.result 字段。
public void testAnswersForQuestion() {
Integer resultAnswer = question.getListAnswers().get(0).getResult();
System.out.println("ans1 result: " + ans1.getResult());
System.out.println("question answer result: " + resultAnswer);
assertTrue(question.getListAnswers().size()>0);
assertTrue(question.getListAnswers().size()==1);
assertTrue(resultAnswer == 2);
ans1.setResult(0);
assertTrue(ans1.getResult()==0);
System.out.println("----ADD ANSWER----");
question.getListAnswersAsSet().add(ans1);
assertTrue(question.getListAnswers().size()==1);
resultAnswer = question.getListAnswers().get(0).getResult();
assertTrue(resultAnswer == 0);
System.out.println("----AFTER----");
System.out.println("ans1 result: " + ans1.getResult());
System.out.println("question answer result: " + resultAnswer);
}
所有的测试都通过了。输出:
ans1 result: 2
question answer result: 2
----ADD ANSWER----
----AFTER----
ans1 result: 0
question answer result: 0
如您所见,现场结果已更改。如果 Answer.result > 0 ,我需要禁止更新记录。
推荐阅读
- google-bigquery - 当使用从 TextIO 到 BigQuery 的无界 PCollection 时,数据卡在 BigQueryIO 内部的 Reshuffle/GroupByKey
- python - 如何在没有标题的情况下读取“.dat 文件”中的特定列,然后存储在列表中以转换赤经和赤纬
- java - -Dhadoop.security.logger' 未被识别为内部或外部命令
- entity-framework-6 - 实体框架 6.2,首先使用 DB 获取运行时列丢失
- java - 如何根据一些变量在 Widget 上应用各种样式?
- sql-server - Dynamics CRM - 用于获取查找相关实体的 SQL 查询
- php - 带有 URL 更改的 Silex 内部重定向?
- python - tkinter(python)框架中的滚动条
- jquery - 访问存储在 Jquery 变量中的类名
- typescript - 映射函数类型时保留参数名称