- Download the latest version of hibernate from hibernate.org, and include all the required jars in your classpath.
- Hibernate configuration
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521/orcl</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="beans/Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>hibernate.cfg.xml - The Employee bean class to hold the data
public class Employee {
public long empId;
public String empName;
public String empJob;
public long empSal;
public long getEmpId() {
return empId;
}
public void setEmpId(long empId) {
this.empId = empId;
}
public String getEmpJob() {
return empJob;
}
public void setEmpJob(String empJob) {
this.empJob = empJob;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public long getEmpSal() {
return empSal;
}
public void setEmpSal(long empSal) {
this.empSal = empSal;
}
}Employee.java - The Employee Mapping file: This listing of the Data Access Object uses the setMaxResults, and setFirstResult method of the Query object to extract the appropriate set of results for each page.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.Employee" table="Emp">
<id name="empId" column="EMPNO" type="long">
<generator class="native"/>
</id>
<property name="empName" column="ENAME" />
<property name="empJob" column="JOB" />
<property name="empSal" column="SAL" type="long"/>
</class>
</hibernate-mapping>Employee.hbm.xml - The Data Access Object
public class DAO {
private static int pageSize = 3;
public static List getData(int pageNumber) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
List result = null;
try {
session.beginTransaction();
Query query = session.createQuery("from Employee");
query = query.setFirstResult(pageSize * (pageNumber - 1));
query.setMaxResults(pageSize);
result = query.list();
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}DAO.java - The JSP
<jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="urn:jsptld:http://java.sun.com/jsp/jstl/core">
<jsp:directive.page contentType="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/screen.css" />
<jsp:scriptlet>
int pageNumber=1;
if(request.getParameter("page") != null) {
session.setAttribute("page", request.getParameter("page"));
pageNumber = Integer.parseInt(request.getParameter("page"));
} else {
session.setAttribute("page", "1");
}
String nextPage = (pageNumber +1) + "";
session.setAttribute( "EmpList", data.DAO.getData(pageNumber));
System.out.println(((java.util.List)session.getAttribute("EmpList")).size());
String myUrl = "pagingEmp.jsp?page=" + nextPage;
System.out.println(myUrl);
pageContext.setAttribute("myUrl", myUrl);
</jsp:scriptlet>
<h2 align="center">Emp Table with Display tag</h2>
<jsp:useBean id="EmpList" scope="session" type="java.util.List"></jsp:useBean>
<table>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Job</th>
<th>Salary</th>
</tr>
<c:forEach items="${EmpList}" var="emp" begin="0" end="10">
<tr>
<td><c:out value="${emp.empId}"></c:out></td>
<td><c:out value="${emp.empName}"></c:out></td>
<td><c:out value="${emp.empJob}"></c:out></td>
<td><c:out value="${emp.empSal}"></c:out></td>
</tr>
</c:forEach>
<tr>
<td colspan="2"></td>
<td colspan="2"><a href="${pageScope.myUrl}">nextPage</a></td>
</tr>
</table>
</jsp:root>pagingEmp.jsp
This JSP uses the DAO class to retrieve the Employee information from the database. The page number is passed as a parameter to the DAO. Notice that I did not implement the "previous" page, but it is similar to next. I assumed that we do not know the number of results for this example.
Thursday, December 14, 2006
Paging in JSP with Hibernate
In the past, I had a few posts on how to implement pagination using displaytag(1, 2). That solution is feasible only with small result sets, the reason being that we will have the entire result set in memory (also called cache based paging). If the result set is large, then having the entire result set in memory will not be feasible. With large result sets, you cannot afford to have them in memory. In such case, you have to fetch a chunk of data at a time (query based paging). The down side of using query based paging, is that there will be multiple calls to the database for multiple page requests. In this post, I will describe how to implement simple query based caching solution, using Hibernate and a simple JSP. Time permitting, I will soon post a hybrid of cache based and query based paging example. Here is the code for implementing simple paging using a JSP and Hibernate:
Subscribe to:
Post Comments (Atom)
Popular Posts
-
This post will describe how to create and deploy a Java Web Application war to Heroku using Heroku CLI. You will need a basic understanding ...
-
JUnit 4 introduces a completely different API to the older versions. JUnit 4 uses Java 5 annotations to describe tests instead of using in...
-
In a previous post, I described how to use Quartz scheduler for scheduling . In this post, I describe the configuration changes required for...
-
Recently I was attempting to deploy to weblogic from a Jenkins installed on a Red Hat Enterprise Linux Server release 7.3 , to a remote Webl...
-
New posts with iText 5.5.12 Following are two new posts for PDF Merge with iText 5.5.12 Merge PDF files using iText 5 Merge and Paginate PDF...
-
In this post we will see how to do an offline install Jenkins and required plugins on a Red Hat Enterprise Linux Server release 7.3. This is...
-
Displaytag is an opensource tag library that can be used to display tables on JSPs. Apart from being able to display tables, the displaytag...
-
I put up a new google co-op search box on top of the blog. I am trying to build a Java search service using Google co-op. I left the custom ...
-
The example here demonstrates the use of an anonymous PL/SQL block to return data to a calling Java program. It also shows how to use nested...
-
The previous post described the Command pattern in brief. I listed out where and why the command pattern may be used. This post describes h...
You wrote: "Time permitting, I will soon post a hybrid of cache based and query based paging example."
ReplyDeleteI would love to see this article. Perhaps, even if you don't get time to write the code, you could post some text explaining the design behind your solution?
Chris.
I was actually looking at this article today, and thinking if I can come up with any better idea paging in J2EE
ReplyDeleteNot sure if you have seen this http://blog.hibernate.org/cgi-bin/blosxom.cgi/2004/08/14#pagination
ReplyDeleteHibernate blog explaining how to implement pagination using hibernate.
I think one question still remains is how do we display the total number of results as well.
Once we implemented paging in Hibernate the same way, but we have found that using the setFirstResult function is not very fast on large tables. This is actually good for the first few pages. The database system scans the whole table from the beginning to the place you want to display. It is faster to have one column with sequential row numbers and an index on it. In some cases, if records are added only at the end or beginning - this is possible.
ReplyDelete--
our consulting company
To Piotr: actually, this depends on implementation of JDBC driver. Oracle drivers do exactly as you said. I don't know if PG or MySQL drivers have the same behaviour. I believe MySQL works because it has a native "first/max" support (if you can do that with SQL, the driver should do the same).
ReplyDeleteactually i am interested in Jsp code which uses hibernate to store dta & retrieve...can u help me by posting related code.
ReplyDeleteThanks in advance!
Sanjay Yadav
i have gone through your paging..it is really usefull...
ReplyDeleteHey Abhi, i thought ur article was excellent and very informative!
ReplyDeleteAbhi - Thanks for posting this it was very helpful, but unfortunately I still can't get it to work on my end. I'm getting the following exception:
ReplyDeleteorg.apache.jasper.JasperException: /common/pagingEmp.jsp(1,121) Could not add one or more tag libraries.
Can you please specify which taglibs you are using? and how can I implement them in my web app? (I'm using Tomcat v6.
Thanks for your help!
Abhi - I got it to work now!! please ignore my previous post. But I still have a favor to ask, can you please walk me through the logic to implement "previous page"?
ReplyDeleteThanks,
Tamer
Hi,I am new to JSP and Hibernate. Can you please show an example on how to insert data into DB from JSP and how to view it from JSP.
ReplyDeleteHi abhi
ReplyDeletei am new in hibernate,i want pagination in my web application so i go through your Paging in JSP with Hibernate.but i did not get this code
session.setAttribute( "EmpList", data.DAO.getData(pageNumber));
particularly where data is coming.and
also i am trying package name instead
of data,then it giving error as
java.lang.NumberFormatException: For input string: "empId".
please help me in this topic.
thanks
Biswanath
I got it . please ignore my previous post
ReplyDeletehi abhi,
ReplyDeletei am parveen
i have been used your program but when i compile the jsp i got an error
org.apache.jasper.JasperException: /pagingEmp.jsp(2,58) Could not add one or more tag libraries
what type of library i need please tell me. i need it very much. help me . i am waitng for ur response
Hi Abhi,
ReplyDeleteIam working on an app wic is quite similar to this post....
I am tryin to export data to CSV format...
Using flex as UI, I choose the component(thro a combo box) whose data has to be exported, and then send it to the Action class on the server. I retrieve wat ever data is to be retrieved, from a session bean and send it to a JSP file where a format data to presented as a downloadable file.
When i access the action class thro the URL, i get the download pop-up.
But when i click the export button in Flex, there is no response.
Plz find few code snippets and let me know what im missing:
Flex:
public function ExportData():void{
exportData.send({id:DCSelect1.selectedItem.@id.toString(),
type:"ABC", from:dateFrom.text, dateto:dateTo.text});
}
public function fileDownload(event:ResultEvent):void {
return;
}
HTTPService: id="exportData" showBusyCursor="true" concurrency="last"
url="http://111.22.66.111:8080/EPDD/exportData.action"
result="fileDownload(event)" fault="exportError(event)"
JSP:
page language="java" contentType="application/csv; charset=ISO-8859-1"
import ----------------
-------------------------
pageEncoding="ISO-8859-1"
response.setContentType("application/csv");
response.setHeader("Content-Disposition","attachment;filename=
Report.csv");
System.out.println("---- Getting the Data to Download ----");
out.print("Date");
out.print(",");
out.print("value");
out.print("\n");
in a loop{
out.print(date);
out.print(",");
out.print(value);
out.print("\n");
}
//Finally
out.flush()
I guess the connection btw JSP and Flex is missing, because it works fine when i access the action class through URL.
Should the FileDownload() function
in Flex have anything to recieve the proper content from the JSP file???
Hello Tamer..
ReplyDeleteI am facing the same issue...
"org.apache.jasper.JasperException: /login.jsp(2,56) Could not add one or more tag libraries"
can u tell me how did u solved it???
Abhi- What may be the reason??
I put a bookmark on the Google bookmark.
ReplyDeleteI always think about what is. It seems to be a perfect article that seems to blow away such worries.
ReplyDeleteI am always searching online for posts that can help me. watching forward to another great blog.
ReplyDeleteHi this really is informative article That’s quite enjoyable.
ReplyDeleteThanks Again. Outstanding.
ReplyDeleteI do consider all of the ideas you have introduced on your post.
ReplyDeleteI absolutely enjoyed every bit of it.
ReplyDeleteI admire this article for the well-researched content and excellent wording.
ReplyDeleteNice post. It’s always interesting to read articles here. you really great
ReplyDeleteI am grateful for for your information! Take care!
ReplyDeleteWoah! It’s simple article, yet effective. Thanks for this
ReplyDeleteThat was an excellent article. You made some great points.
ReplyDeleteI would like to refer to your article on my blog and write it.
ReplyDeleteI think your writing is the cleanest I’ve ever seen.
ReplyDeleteIt was a very good post indeed. I thoroughly enjoyed reading it in my lunch time.
ReplyDeletewoooow, amazing blog to read, thanks for sharing, and move on.
ReplyDeleteGREAT ARTICLE,THIS WHAT TOTALLY WHAT I WAS LOOKING FOR.
ReplyDeleteGreat post ! I am pretty much pleased with your good post.
ReplyDeleteThe article you shared, it was very interesting and meaningful.
ReplyDeleteA lot more peoople must read his and understand this side of thhe story.
ReplyDeleteNice blog, I will keep visiting this blog very often.
ReplyDeleteI am overwhelmed by your post with such a nice topic.
ReplyDeleteWell done! Also visit my site
ReplyDeleteIt was really informative. Your website is very useful. Many thanks for sharing!
ReplyDeleteThis is a good tip particularly to those fresh to the blogosphere.
ReplyDeleteMany thanks for sharing this one. A must read post!
ReplyDeleteGreate pieces. Keep writing such kind of info on your site. Im really impressed by your blog.
ReplyDeleteQuality content is the main to interest the viewers to pay a visit the website, that’s what this site is providing.
ReplyDelete