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