Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Spring 3 MVC controller method Transactional

I am using Spring 3.1 and have my DAO and service layer(transactional) written.

However in a special case to avoid a lazy init exception I have to make a spring mvc request handler method @transactional. But It is failing to attach transaction to that method. Method name is ModelAndView home(HttpServletRequest request, HttpServletResponse response). http://forum.springsource.org/showthread.php?46814-Transaction-in-MVC-Controller From this link it seems it is not possible to attach transaction (by default ) to mvc methods. Solution suggested in that link seems to be for Spring 2.5 (overriding handleRequest ). Any help will be reallyappreciated. Thanks

@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");    
}
like image 386
Subin Sebastian Avatar asked Oct 19 '12 10:10

Subin Sebastian


2 Answers

You'll need to implement an interface so that Spring has something it can use as a Proxy 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){
.....
}
}
like image 138
Kieran Avatar answered Oct 18 '22 23:10

Kieran


Spring will implement the transactional logic using JDK dynamic proxies, these rely on proxied classes implementing suitable interfaces. It's also possible to use CGLib proxies which don't require interfaces.

There is a nice article about this link

like image 27
BartoszMiller Avatar answered Oct 18 '22 22:10

BartoszMiller