Spring:最好使用@Transactional和rollback

时间:2015-10-06 19:24:00

标签: java spring hibernate spring-mvc jpa

在这两个例子中,我使用了Spring + JPA + Hibernate。两个中哪一个是正确的形式?在第一个示例中,取消选中MyException而不是在第二个示例中检查MyException。谢谢,抱歉我的英文

第一个例子

CartController.java

@RequestMapping(value="/buy",method=RequestMethod.POST)
  public String buy(){
  CartDAO.buy();
  return "redirect:/";
 }//buy

CartDAOImpl.java

@Transactional(rollbackfor=MyException.class)
public class CartDAOImpl implements CartDAO {

@PersistenceContext
private EntityManager em;

public void buy(){
 ....
 if(x !=y) throw new MyException();
 em.persist(Item);
 ....
}
}

ExceptionController.java

@ControllerAdvice
public class ExceptionController {

@ExceptionHandler(MyException.class)
public String articlenotavailable(){
    return "error/articlenotavailable";
}

}//ExceptionController

MyException.java

public class MyException extends RuntimeException {
private static final long serialVersionUID = 1L;
}

第二个例子

CartController.java

@RequestMapping(value="/buy",method=RequestMethod.POST)
  public String buy()throws MyException{
  CartDAO.buy();
  return "redirect:/";
 }//buy

CartDAOImpl.java

@Transactional(rollbackfor=MyException.class)
public class CartDAOImpl implements CartDAO {

@PersistenceContext
private EntityManager em;

public void buy()throws MyException{
 ....
 if(x !=y) throw new MyException();
 em.persist(Item);
 ....
}
}

ExceptionController.java

@ControllerAdvice
public class ExceptionController {

@ExceptionHandler(MyException.class)
public String articlenotavailable(){
    return "error/articlenotavailable";
}

}//ExceptionController

MyException.java

public class MyException extends Exception {
private static final long serialVersionUID = 1L;
} 

0 个答案:

没有答案