javax.transaction.TransactionRequiredException
' 永远不会在相应的 try block 中抛出
引用:http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#merge%28T%29
注意:我不想在我的方法签名中声明抛出新异常
如何处理异常
?
我认为 .save .merge
可以在所有 DAO
中使用。因此,使用不同的对象(但相同的模式)为每个 DAO 编写相同的代码并不是明智的OOP。
如何正确制作通用.merge .save
或所有此类重复的事情。
我在谷歌上找不到太多稳定的例子。
有示例代码吗?
private EntityManager entityManager;
public Boards save(Boards board) {
Boards boardToBeReturned = null;
try{
boardToBeReturned = entityManager.merge(board);
}catch (IllegalArgumentException e){
e.printStackTrace();
}catch (TransactionRequiredException e){
e.printStackTrace();
}
return boardToBeReturned;
}
类的完整示例代码:
package web.dao.impl.jpa;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.transaction.TransactionRequiredException;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import web.dao.BoardsDAO;
import web.entity.Boards;
import web.entity.Users;
@Repository
public class BoardsDAOImpl implements BoardsDAO {
/**
* The JPA entity manager
*/
// @Autowired
@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;
public Boards save(Boards board) {
Boards boardToBeReturned = null;
try{
boardToBeReturned = entityManager.merge(board);
}catch (IllegalArgumentException e){
e.printStackTrace();
// }catch (TransactionRequiredException e){
// e.printStackTrace();
}
return boardToBeReturned;
}
public Boards getBoardById(Long id){
Boards boardToBeReturned = null;
System.out.println("board id entered for lookup was : "+id);
try {
boardToBeReturned=entityManager.find(Boards.class, id);
}catch (IllegalArgumentException e){
e.printStackTrace();
}
return boardToBeReturned;
}
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
/**
* Helper method to return the hibernate session from the JPA
* entity manager implementation.
*
* @return the hibernate {#link Session}
*/
protected Session getHibernateSession() {
return entityManager.unwrap(Session.class);
}
public List<Boards> getBoardListByUser(Users user){
return null;
}
}
最佳答案
IllegalArgumentException 和 TransactionRequiredException 是运行时异常,表示存在编程错误。你不应该捕获他们。如果你捕获了他们,最糟糕的事情就是像你现在一样忽视他们,假装什么都没发生。您的方法应该如下所示:
public Boards save(Boards board) {
return entityManager.merge(board);
}
既然您正在使用 Spring 并寻找通用 DAO,那么请查看 Spring Data JPA项目,它提供了这些,以及更多。
关于java - JPA 和 Spring 对带有异常和泛型的 DAO 的处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21196672/