介紹如何查詢
1.查詢資料庫的值並使用Table秀出來,
sess.createQuery("from UserData"),這裡要注意UserData大小寫要和UserData.hbm.xml一致
=== queryUserData.jsp ===
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="demo.*" %>
<%
org.hibernate.Session sess = null;
org.hibernate.SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
sess = sessionFactory.openSession();
java.util.Iterator listud = null;
try {
org.hibernate.Query sqlq = sess.createQuery("from UserData");
listud = sqlq.iterate();
%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Query UserData</title>
List Data
<%
if(listud!=null){
%>
<table border="1">
<thead>
<tr>
<th>User ID</th>
<th>User Password</th>
<th>User Name</th>
</tr>
</thead>
<%
while(listud.hasNext()){
UserData ud = (UserData)listud.next();
%>
<tbody>
<tr>
<td><%=ud.getUserid()%></td>
<td><%=ud.getUserpassword()%></td>
<td><%=ud.getUsername()%></td>
</tr>
</tbody>
<%
}
%>
</table>
<%
}else{
%><font size="10">Not Data .</font><%
}
%>
<%
} catch (Exception ex) {
System.out.println(ex);
} finally {
sess.flush();
sess.close();
}
%>
2.下條件去做查詢,
主要不一樣的地方在sess.createQuery("from UserData where username like ''");
=== queryUserData2.jsp ===
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="demo.*" %>
<%
org.hibernate.Session sess = null;
org.hibernate.SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
sess = sessionFactory.openSession();
java.util.Iterator listud = null;
org.hibernate.Query sqlq = null;
try {
String qname = request.getParameter("qname");
if(qname!=null && !qname.equals("")){
sqlq = sess.createQuery("from UserData where username like '%"+qname+"%'");
}else{
sqlq = sess.createQuery("from UserData");
}
listud = sqlq.iterate();
%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Query UserData</title>
<form name="qud2" action="queryUserData2.jsp" method="POST">
User Name : <input type="text" name="qname" value="" size="30" />
<input type="submit" value="Query" name="query" />
</form><hr>
List Data
<%
if(listud!=null){
%>
<table border="1">
<thead>
<tr>
<th>User ID</th>
<th>User Password</th>
<th>User Name</th>
</tr>
</thead>
<%
while(listud.hasNext()){
UserData ud = (UserData)listud.next();
%>
<tbody>
<tr>
<td><%=ud.getUserid()%></td>
<td><%=ud.getUserpassword()%></td>
<td><%=ud.getUsername()%></td>
</tr>
</tbody>
<%
}
%>
</table>
<%
}else{
%><font size="10">Not Data .</font><%
}
%>
<%
} catch (Exception ex) {
System.out.println(ex);
} finally {
sess.flush();
sess.close();
}
%>