首页 > 解决方案 > 用于条件更新的 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 注释。如果需要,可以在更新和恢复之前保存数据,但可能以另一种方式存在?

标签: hibernatejpa

解决方案


我的程序解析相同的资源并生成带有答案的问题列表。我需要用数据库中的答案检查问题记录。如果存在问题,我只添加了答案。如果问题的答案也存在,我需要更新值 == 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 ,我需要禁止更新记录。


推荐阅读