在开发中一般都是用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");