java - 使 Spring 3 MVC Controller 方法成为事务性的

标签 java spring hibernate jakarta-ee spring-mvc

我正在使用 Spring 3.1 并编写了我的 DAO 和服务层(事务)。

但是在特殊情况下,为了避免延迟初始化异常,我必须创建一个 spring mvc 请求处理程序方法@transactional。但是它无法将事务附加到该方法。方法名称是 ModelAndView home(HttpServletRequest 请求,HttpServletResponse 响应)。 http://forum.springsource.org/showthread.php?46814-Transaction-in-MVC-Controller 从这个链接看来不可能将事务(默认情况下)附加到 mvc 方法。该链接中建议的解决方案似乎适用于 Spring 2.5(覆盖 handleRequest )。任何帮助将不胜感激。谢谢

@Controller
public class AuthenticationController { 
@Autowired
CategoryService categoryService;    
@Autowired
BrandService brandService;
@Autowired
ItemService itemService;

@RequestMapping(value="/login.html",method=RequestMethod.GET)
ModelAndView login(){       
    return new ModelAndView("login.jsp");       
}   
@RequestMapping(value="/home.html",method=RequestMethod.GET)
@Transactional
ModelAndView home(HttpServletRequest request, HttpServletResponse response){
    List<Category> categories = categoryService.readAll();
    request.setAttribute("categories", categories);     
    List<Brand> brands = brandService.readAll();
    request.setAttribute("brands", brands);     
    List<Item> items = itemService.readAll();
    request.setAttribute("items", items);
    Set<Image> images = items.get(0).getImages();
    for(Image i : images ) {
        System.out.println(i.getUrl());
    }
    return new ModelAndView("home.jsp");    
}

最佳答案

您需要实现一个接口(interface),以便 Spring 可以将其用作代理接口(interface):

@Controller
public interface AuthenticationController {
  ModelAndView home(HttpServletRequest request, HttpServletResponse response);
}

@Controller
public class AuthenticationControllerImpl implements AuthenticationController {

@RequestMapping(value="/home.html",method=RequestMethod.GET)
@Transactional
@Override
ModelAndView home(HttpServletRequest request, HttpServletResponse response){
.....
}
}

关于java - 使 Spring 3 MVC Controller 方法成为事务性的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12971848/

相关文章:

java - 静态实例线程安全

java - 检查 NaN 并在 If 中使用它

java - 如何删除 ExpandableListView 中父子之间的特定空间

java - 使用 Spring XML 实体在带注释的文件中设置属性?

java - Ajax 调用的 Spring security session 超时处理

java - Spring Batch - 进程在哪里运行

java - JPA加入spring boot应用

java - 恩弗斯添加用户信息

java - 如何简单地在消息中编写多行文本?

java - 使用 JPA/Hibernate 在集合中搜索