java - Spring RESTful Controller 方法改进建议

标签 java spring hibernate rest spring-mvc

我是 Spring、REST 和 Hibernate 的新手。也就是说,我尝试组合一个企业级 Controller 方法,我计划将其用作 future 开发的模式。

您认为可以通过哪些方法来改进?我确信有很多。

@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;
    }

异常(exception):

ServerErrorException uses Spring's annotations to throw an HTTP 500, and the ResourceNotFoundException does the same with a 404.  

谢谢,我很感激任何意见。

最佳答案

改进建议:

  • a) 使用 JPA 而不是普通的 Hibernate
  • b) 让 Spring 注入(inject) Hibernate Session/JPA 实体管理器
  • c) 让 Spring 进行数据库处理(注解 (@Transactional) 或编程 (TransactionTemplate))

关于java - Spring RESTful Controller 方法改进建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20804768/

相关文章:

java - Mockito when() 不工作

java - JPA Hibernate Postgres 错误 - 运算符不存在 : boolean = integer

java - org.hibernate.QueryException : could not resolve property: MetadataForHibernate of: bookshare.实体.hasbooks.HasBooks

java - java中如何限制if条件只执行一次

java - 一个java应用程序可以有多少个线程池

java - 为 DAO 创建接口(interface)是否合理,而我已经为服务创建了 DAO?

java - 更新到 Hibernate 5 后无法访问 TransactionManager 或 UserTransaction

java - JPA 查询问题

java - FileInputStream ("hello.txt"),除非我指定绝对路径(C :\User\Documents etc)

java - Android 从匿名类中获取 Activity