Spring RESTful控制器方法改进建议
我是Spring,REST和Hibernate的新手。 也就是说,我试图整合一个企业级控制器方法,我打算将其用作未来开发的模式。
您认为哪些方法可以改进? 我相信有很多东西。
@RequestMapping(value = "/user", method = RequestMethod.GET) public @ResponseBody User getUser(@RequestParam(value="id", required=true) int id) { Session session = null; User user = null; try { HibernateUtil.configureSessionFactory(); session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); user = (User) session.get(User.class, id); session.getTransaction().commit(); } catch (HibernateException e) { if (session != null) { session.getTransaction().rollback(); } e.printStackTrace(); throw new ServerErrorException(); } if (user == null) { throw new ResourceNotFoundException(); } return user; }
例外:
ServerErrorException uses Spring's annotations to throw an HTTP 500, and the ResourceNotFoundException does the same with a 404.
谢谢,我感谢任何输入。
建议的改进:
- a)使用JPA而不是普通的Hibernate
- b)让Spring注入Hibernate Session / JPA实体管理器
- c)让Spring执行数据库处理(Annotation(@Transactional)或programmatic(TransactionTemplate))