在開發中一般都是用hibernate的query來執行sql語句,來訪問數據庫。因爲query是將查詢結果中的每一條記錄都放到bean中(query.setBeanclass就是用來設置這個bean的),然後將這些包含了查詢結果的bean放到list中,並返回。所以我們在開發中只要做以下步驟1。想query傳遞select語句;2。設置bean;3。執行query。這樣就可以得到包含了所有查詢結果的list,取出裏面的bean就可以用了
List list = null;
String strSql = "";
strSql = "Select * From Student";
Query query = session.createQuery(strSql);
query.setBeanclass("在這裏寫一下你bean所在的位置");
list = query.list();
return list;
其中的query和session都是經過重新封裝的。這裏提供一個簡單的查詢方法!
Session session=HibernateSessionFactory.currentSession();
Transaction transaction=session.beginTransaction();
Query query=session.createQuery("from Student");
List list=query.list();
transaction.commit();
return list;
java code:
Dao類:
public List getUserByName(String userName) {
List list = new ArrayList();
String sql = "select * from UserInfo where name =?";
con = ConnectionManager.getCn();
try {
ps = con.prepareStatement(sql);
ps.setString(1, userName);
rs = ps.executeQuery();
while (rs.next()) {
LoginInfo loginInfo = new LoginInfo();
loginInfo.setId(rs.getInt("id"));
loginInfo.setName(rs.getString("name"));
loginInfo.setPwd(rs.getString("pwd"));
list.add(loginInfo);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ConnectionManager.closeRs(rs);
ConnectionManager.closePs(ps);
ConnectionManager.closeCn(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
Action 類
- Java code
- /** * 登錄方法 */ public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { LoginForm checkform = (LoginForm) form; UserInfoService userInfoService = new UserInfoService(); LoginInfo loginInfo = new LoginInfo(); loginInfo = checkform.getLoginInfo(); boolean bool = userInfoService.Login(loginInfo); if (bool) { request.setAttribute("loginInfo", loginInfo); return new ActionForward("/ok.jsp"); } else { return new ActionForward("/Error.jsp"); } }
- Action 類:(存)
- /** * 登錄方法 */ public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { LoginForm checkform = (LoginForm) form; UserInfoService userInfoService = new UserInfoService(); LoginInfo loginInfo = new LoginInfo(); loginInfo = checkform.getLoginInfo(); boolean bool = userInfoService.Login(loginInfo); if (bool) { request.setAttribute("loginInfo", loginInfo); return new ActionForward("/ok.jsp"); } else { return new ActionForward("/Error.jsp"); } }
- Jsp 頁面:取值
- int allCounts = (Integer) request.getAttribute("allCounts"); List allLogs = (List) request.getAttribute("allLogs");