0

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.

Sitansu
  • 3,225
  • 8
  • 34
  • 61
Lurk21
  • 2,307
  • 12
  • 37
  • 55

1 Answers1

1

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) )
Ralph
  • 118,862
  • 56
  • 287
  • 383
  • * a) Do you mean use javax.persistence annotations ? – Lurk21 Dec 27 '13 at 17:24
  • yes, and use EntiyManager instead of Session and SessionFactory. – Ralph Dec 27 '13 at 19:49
  • Ok, @Ralph I have a lot of reading and testing to do. All of this is new to me. When I am done with what you've suggested, may I update this question for your second-review? Thanks, Lynn – Lurk21 Dec 27 '13 at 20:08