基于hiberbate 根据id查询对象的三种方式总结:
假如我们根据id查出一条数据并展示在jsp页面:Action层代码:
1 2 3 4 5 6 7 8 9 |
public String updateAthlete() throws Exception { ActionContext context = ActionContext.getContext(); HttpServletRequest request = ServletActionContext.getRequest(); String id = request.getParameter("id"); AthleteManage updateAthleteById = AthleteactionDao.updateAthleteById(Integer.parseInt(id)); context.put("updateAthleteById", updateAthleteById); return "updateAthlete"; } |
DAO层:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public static AthleteManage updateAthleteById(int id) { Session session = HibernateSessionFactory.getSession(); try { session.beginTransaction(); /*方式一:直接根据session.get()查出对象 最为直观的一种方法**/ /* AthleteManage AthleteManage = (AthleteManage) session.get(AthleteManage.class, id);*/ /*方法二:HQL查询*/ /*AthleteManage athleteManage = new AthleteManage(); List list = session.createQuery("from AthleteManage where id="+id+"").list(); if (!list.isEmpty()) { athleteManage=(AthleteManage) list.get(0); }*/ /*方法三:***/ AthleteManage athleteManage = new AthleteManage(); Criteria criteria = session.createCriteria(AthleteManage.class); criteria.add(Restrictions.eq("id", id)); List list = criteria.list(); if (!list.isEmpty()) {athleteManage = (AthleteManage) list.get(0); } session.getTransaction().commit(); return athleteManage; } catch (HibernateException e) { session.getTransaction().rollback(); e.printStackTrace(); } return null; } |
JSP代码:
1 2 3 4 5 6 7 |
<s:form action="useraction" > <input type="text" value="${request.updateAthleteById.athleteName}" name="name"> <input type="text" value="${request.updateAthleteById.id}" name="id"> <s:submit value="提交" method="updateUserup"/> </s:form> |
结果: