【问题标题】:Spring RESTful controller method improvement suggestionsSpring RESTful 控制器方法改进建议
【发布时间】:2014-01-15 06:52:05
【问题描述】:

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

谢谢,感谢您的任何意见。

【问题讨论】:

  • 我将此标记为转移到 Code Review Stack Exchange,在那里它将得到应有的爱。
  • 甚至不知道那是一回事。谢谢。

标签: java spring hibernate rest spring-mvc


【解决方案1】:

建议的改进:

  • a) 使用 JPA 而不是普通的 Hibernate
  • b) 让 Spring 注入 Hibernate Session/JPA Entity Manager
  • c) 让 Spring 做数据库处理(注解 (@Transactional) 或程序化 (TransactionTemplate))

【讨论】:

  • * a) 你的意思是使用 javax.persistence 注释吗?
  • 是的,使用 EntiyManager 代替 Session 和 SessionFactory。
  • 好的,@Ralph 我有很多阅读和测试要做。这一切对我来说都是新鲜的。当我完成您的建议后,我可以更新此问题以供您进行第二次审查吗?谢谢,林恩
猜你喜欢
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 2016-07-06
  • 2015-06-10
  • 2011-03-19
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多