在hibernate / jpa和JUnit5中处理异常的正确方法

时间:2017-11-28 23:10:06

标签: java hibernate jpa junit5

我想知道,当我尝试在数据库中创建和持久化对象时,处理异常的最佳方法。

所以我有一个名为Rule的表,带有getter和setter:

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @Column(name = "type", nullable = false, unique = true)
    private String type;

    @Column(name = "hint", nullable = false)
    private String hint;

    @Column(name = "help", nullable = false)
    private String help;

    @Enumerated(EnumType.STRING)
    @Column(name = "language", nullable = false)
    private Language language;

    @OneToMany(mappedBy = "rule")
    @Column(name = "user_rule")
    private Set<UserRule> user_rule;

    @OneToMany
    @JoinColumn(name = "rule_id")
    private Set<Sentence> sentence;

我有方法创建谁在数据库中添加对象:

 public static Rule create(EntityManagerFactory factory, String type, String hint, String help, Language language) {
            EntityManager em = factory.createEntityManager();
            EntityTransaction transaction = null;
            Rule new_rule = new Rule();

            try {
                transaction = em.getTransaction();
                transaction.begin();

                new_rule.setType(type);
                new_rule.setHint(hint);
                new_rule.setHelp(help);
                new_rule.setLanguage(language);

                em.persist(new_rule);
                transaction.commit();
            } catch (Exception ex) {
            if (transaction != null) {
                transaction.rollback();
            }
            throw ex;

            } finally {
                em.close();
            }

            return new_rule;
    }
  1. 我应该为每个异常使用多个catch,方法可以放入try块吗?
  2. 如果我的解决方案是处理它的好方法,我怎样才能以良好的方式打印与异常ex相关的特定消息?
  3. 如何在JUnit5中为try块的内容引发异常,以测试是否引发了异常(我是否应该引发所有异常?)
  4. 如果我将null元素(设置为nullable = false)传递给方法create如何传输错误或异常(通过hibernate / jpa或我应该像往常一样自己处理它?)
  5. 如果您有任何其他建议,请告诉我们!

    提前感谢您的帮助。

0 个答案:

没有答案