我想知道,当我尝试在数据库中创建和持久化对象时,处理异常的最佳方法。
所以我有一个名为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;
}
ex
相关的特定消息?try
块的内容引发异常,以测试是否引发了异常(我是否应该引发所有异常?)create
如何传输错误或异常(通过hibernate / jpa或我应该像往常一样自己处理它?)如果您有任何其他建议,请告诉我们!
提前感谢您的帮助。