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做数据库处理(注解(@Transactional)或程序化(TransactionTemplate))