Spring RESTful控制器方法改进建议 [英] Spring RESTful controller method improvement suggestions

查看:103
本文介绍了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;

尝试{
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();
抛出新的ServerErrorException();
}

if(user == null){
throw new ResourceNotFoundException();
}

返回用户;

例外:

  ServerErrorException使用Spring的注释来引发HTTP 500,而ResourceNotFoundException与404一样。

谢谢,我很欣赏任何输入。

解决方案

建议的改进:
$ b


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

I am new to Spring, REST, and Hibernate. That said, I've tried to put together an Enterprise-class controller method, which I plan to use as a pattern for future development.

What ways do you see that this can be improved? I'm sure there are plenty.

@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.  

Thanks, I appreciate any input.

解决方案

Suggested Improvements:

  • a) use JPA instead of plain Hibernate
  • b) Let Spring inject the Hibernate Session/JPA Entity Manager
  • c) Let Spring do the database Handling (Annotation (@Transactional) or programmatic (TransactionTemplate) )

这篇关于Spring RESTful控制器方法改进建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆