JTable and JPA Pagination Through Custom TableModel
I really want to talk about JTable, Beans Binding and JPA pagination but I think I need to write about JTable and JPA pagination first. So I will take the Beans binding stuff in another post.
By the way, choose wisely your JPA Provider/DB Provider combination, as some combinations will not give you any real paginations at all. For example, neither OpenJPA, Hibernate or TopLink/EclipseLink seems to support Apache Derby pagination (OFFSET/FETCH). The example here uses Derby and TopLink which is a bad example because the JPA pagination doesn’t get translated to SQL command for pagination. So if you really want proper pagination you should use other combination like Hibernate JPA/HSQLDB.
To get a JTable showing data from a paginated JPA Query you need to create a Custom TableModel for the JTable like this one:
The getValueAt in this custom TableModel make use from a paginated (setMaxResults) JPA query that take 100 rows each time. The database contains 30000 rows but with this TableModel you won’t need to retrieve all of them to display the JTable. Only the rows that need to be shown will be retrieved.
To fully understand this custom TableModel I think it’s better to illustrate a full application so I’m going how to describe how to create an example application with netbeans:
First we need a database, I used Java DB. Go to Netbeans ⇒ Services. Right click on Java DB and select Start server.
p.
Create a database. database name “namesdb” username and password “nbuser”.
Connect to the newly created database
Execute command
download the following sql script to create a table and insert 30000 rows. And execute it in sql command window
Now we have a table with 30000 entries that we want to show in a JTable
Let’s create a project in netbeans. New project ⇒ Java ⇒ Java Application
Let’s create the JPA Entity class for the database. Select the project and click on New ⇒
In the wizard select the connection and the customers table
Create a Persistence Unit also and specify TopLink as provider
Now you have created the entity classes for Customers
Now we need to add the Java DB / Derby drivers to the project so TopLink is able to find the drive to connect to the database. Right-click on the project Properties ⇒ Libraries ⇒ Add Library and select or create a library for derby
Now we can create our GUI
New ⇒ JPanel Form. Type JTablePaginationExample as class name
Drop a JTable into the form from the Palette
Now let’s add a custom TableModel to this JTable. Switch to the Source view and add the following