繁体   English   中英

Spring RESTful控制器方法改进建议

[英]Spring RESTful controller method improvement suggestions

我是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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM