Loading

Netbeans & woodstox: ClassCastException: com.sun.xml.bind.v2.runtime.JAXBContextImpl cannot be cast to javax.xml.bind.JAXBContext

Are you getting a ClassCastException in a Netbeans Platform Application, when you are you sure that the class can be casted? Then check http://wiki.netbeans.org/PlainView.jsp?page=DevFaqModuleCCE. This is most likely the result of the the classes being loaded by different classloaders. So JAXBContextImpl cannot be cast to JAXBContext because that JAXBContext is from Classloader “A” and JAXBContextImpl can only be cast to JAXBContext from Classloader “B”.

SEVERE [global]
java.lang.ClassCastException: com.sun.xml.bind.v2.runtime.JAXBContextImpl cannot be cast to javax.xml.bind.JAXBContext
        at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:145)
        at javax.xml.bind.ContextFinder.find(ContextFinder.java:277)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:372)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:337)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:244)
        at com.rubenlaguna.en4j.mainmodule.ImportEvernoteFile.actionPerformed(ImportEvernoteFile.java:65)
        at org.openide.awt.AlwaysEnabledAction.actionPerformed(AlwaysEnabledAction.java:115)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.AbstractButton.doClick(AbstractButton.java:389)
        at com.apple.laf.ScreenMenuItem.actionPerformed(ScreenMenuItem.java:95)
        at java.awt.MenuItem.processActionEvent(MenuItem.java:627)
        at java.awt.MenuItem.processEvent(MenuItem.java:586)
        at java.awt.MenuComponent.dispatchEventImpl(MenuComponent.java:317)
        at java.awt.MenuComponent.dispatchEvent(MenuComponent.java:305)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:638)
        at org.netbeans.core.TimableEventQueue.dispatchEvent(TimableEventQueue.java:104)
[catch] at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
BUILD SUCCESSFUL (total time: 28 minutes 5 seconds)

So this could happen for example if you have both woodstox in a Netbeans Library Wrapper module and you make you application dependent on ide11 ⇒ JAXB 2.1 Library
jaxb21.

In my case I was able to solve by just removing JAXB 2.1 Library from the application.

ClassCastException: JAXBContextImp to JAXBContext with woodstox and NetBeans

If you are getting

java.lang.ClassCastException: com.sun.xml.bind.v2.runtime.JAXBContextImpl cannot be cast to javax.xml.bind.JAXBContext
        at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:145)
        at javax.xml.bind.ContextFinder.find(ContextFinder.java:277)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:372)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:337)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:244)
        at com.rubenlaguna.en4j.mainmodule.ImportEvernoteFile.actionPerformed(ImportEvernoteFile.java:65)

and you are using woodstox be sure to check the DevFaqModuleCCE. This could happen when you have Netbeans Platform Application with a module containing woodstox but also including JAXB 2.1 in the module dependencies for the application.

git: error pushing via HTTP (return code 22)

If you get a

error: Cannot access URL http://github.com/xxxxxxx/, return code 22

when trying to push changes to a git repository via HTTP.

This is probably because you are using an HTTP proxy to access the repo and that proxy doesn’t support WebDAV HTTP methods (especially PROPFIND). So when git issues a PROPFIND the http proxy answers back with a 500 Internal Server Error or something like that.

It seems that PROPFIND is absolutely required so if you can use git:// directly or use a HTTP proxy which supports PROPFIND. Then I think the only option left is try use CONNECT in the proxy.

Netbeans refuses to recognize persistence.xml (no visual editor)

If you create the persistence.xml manually in Windows the file will be created with CRLF line endings (windows style line endings) ,that will prevent Netbeans for recognizing Netbeans will not recognize it as the special file it is and won’t be able to to open it with the special/custom visual editor.

netbeans visual editor for persistence files

netbeans visual editor for persistence files

I opened an bug report netbeans issue #172538. At the beginning, I thought the problem was due to diferent line ending CRLF vs LF issues, but as pointed out in the bug report the line ending has nothing to do with it. It’s just the IDE restart what is needed, no need to change the line endings.

The workaround is easy: change the newline (also line break or end-of-line EOL) characters to Unix style (LF) with any utility. I used Cygwin’s dos2unix (dos2unix src/META-INF/persistence.xml) and then just restart the IDE. Unfortunately just closing and reopening the project containing the persistence.xml file won’t work you have to restart Netbeans.

OpenJPA: Generated SQL contains extra UPDATEs

I’m trying to use OpenJPA to insert some entries in the database and I’m getting a strange number of UPDATEs beside the INSERTs.

I isolated the problem to the following snippet of code

    private void start() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistencexmltest1PU");
        EntityManager em = emf.createEntityManager();        
        for (int i = 0; i < 10; i++) {
            em.getTransaction().begin();
            MyEntity n =new MyEntity();
            n.setValue(i);
            em.persist(n);        
            em.getTransaction().commit();
        }
    }

The generated SQL looks like this:

INSERT INTO MYTABLE (ID, VALUE, CREATED) VALUES (?, ?, ?) [params=(int) 1, (int) 0, (null) null]
INSERT INTO MYTABLE (ID, VALUE, CREATED) VALUES (?, ?, ?) [params=(int) 2, (int) 1, (null) null]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 1]
INSERT INTO MYTABLE (ID, VALUE, CREATED) VALUES (?, ?, ?) [params=(int) 3, (int) 2, (null) null]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 2]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 1]
INSERT INTO MYTABLE (ID, VALUE, CREATED) VALUES (?, ?, ?) [params=(int) 4, (int) 3, (null) null]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 3]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 2]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 1]
INSERT INTO MYTABLE (ID, VALUE, CREATED) VALUES (?, ?, ?) [params=(int) 5, (int) 4, (null) null]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 3]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 4]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 2]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 1]
INSERT INTO MYTABLE (ID, VALUE, CREATED) VALUES (?, ?, ?) [params=(int) 6, (int) 5, (null) null]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 3]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 4]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 2]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 5]
UPDATE MYTABLE SET CREATED = ? WHERE ID = ? [params=(null) null, (int) 1]
...

note the extra UPDATE statements after each INSERT, the number of UPDATEs grows too. From zero UPDATEs after the first INSERT, one in the second, two in the third, and so on. I don’t need to say that this is of course really inefficient. I don’t know what is ultimate cause of this but this started when I added a @Temporal(TemporalType.TIMESTAMP) annotation to the entity class. And I can make it go away by calling EntityManager.clear() after each em.getTransaction().commit()

Ok I found a bug report stating that this behaviour is only observed when the entity classes are not enhanced. So the best solution is use the enhancer. But it really doesn’t work for me, I still get the extra UPDATEs even with enhanced classes. So I’m stuck with the EntityManager.clear() for now.If the class is PROPERLY ENHANCED this problems goes away.

Check the logs (enable them with <property name="openjpa.Log" value="DefaultLevel=TRACE"/> in persistence.xml) and make sure that you don’t see any entry like

5968  persistencexmltest1PU  INFO   [main] openjpa.Enhance - Creating subclass for "[class com.rubenlaguna.MyEntity]". This means that your application will be less efficient and will consume more memory than it would if you ran the OpenJPA enhancer. Additionally, lazy loading will not be available for one-to-one and many-to-one persistent attributes in types using field access; they will be loaded eagerly instead.

If you see the Creating subclass for message means that the class wasn’t enhanced, as I read OpenJPA really need enhanced classes, un – enhanced are just for testing and trivial examples.

For reference:

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="persistencexmltest1PU" transaction-type="RESOURCE_LOCAL">
    <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
    <class>com.rubenlaguna.MyEntity</class>
    <properties>
      <property name="openjpa.ConnectionPassword" value=""/>
      <property name="openjpa.ConnectionDriverName" value="org.hsqldb.jdbc.JDBCDriver"/>
      <property name="openjpa.ConnectionUserName" value="sa"/>
      <property name="openjpa.ConnectionURL" value="jdbc:hsqldb:file:/Users/ecerulm/everjavatest"/>
      <property name="openjpa.Log" value="SQL=TRACE"/>
      <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(SchemaAction=&apos;add,deleteTableContents&apos;,ForeignKeys=true)"/>
    </properties>
  </persistence-unit>
</persistence>

MyEntity.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 
package com.rubenlaguna;
 
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
 
/**
 *
 * @author Ruben Laguna <ruben.laguna at gmail.com>
 */
@Entity
@Table(name = "MYTABLE")
public class MyEntity {
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
 
 
    @Column(name = "VALUE")
    private Integer attr1;
 
 
    @Column(name = "CREATED")
    @Temporal(TemporalType.TIMESTAMP)
    private Date created;
 
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public Integer getValue() {
        return attr1;
    }
 
    public void setValue(Integer value) {
        this.attr1 = value;
    }
 
}

References:

Adding a Google Search Web Element to a WordPress theme

The newly released Google Web element: custom search is awesome.

csewebelement

To add it to my wordpress theme (which doesn’t have a top sidebar for widgets) I had to edit (Appearance ⇒ Editor) the header.php file and add the snippet I got from Google there, at just at the end of the header.php. So the search web element is show right after the banner and before the posts.

In my case the code is

<!-- Google search web element BEGIN-->
<div id="cse" style="width:100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
 
<script type="text/javascript">
  google.load('search', '1');
  google.setOnLoadCallback(function(){
    new google.search.CustomSearchControl('partner-pub-6449419902780618:ybxd02gp4hx').draw('cse');
  }, true);
</script>
<!-- Google search web element END-->

If your theme has a top sidebar for widgets you can add the snippet as a text widgets instead there (to avoid fiddling editing the theme).

OpenJPA Enhancer Ant task in a Netbeans project

In the build.xml of the project (likely this will be a Java Class Library project), override -post-compile or -pre-jar and invoke <openjpac/>. You will need to add the build/classes and the openjpa jars to <taskdef/> and <openjpac/>. The <openjpac/> will enhance all classes mentioned in persistence.xml (which has to be in the classpath)

<?xml version="1.0" encoding="UTF-8"?>
 
 
<project name="JpaEntitiesLibrary" default="default" basedir=".">
    <description>Builds, tests, and runs the project JpaEntitiesLibrary.</description>
    <import file="nbproject/build-impl.xml"/>
 
    <target name="-post-compile">
        <echo message="begin openJPAC"/>
        <path id="openjpa.path.id">        
            <pathelement location="${build.classes.dir}"/>
 
             <!-- Adding the OpenJPA jars into the classpath -->
            <fileset dir="C:\Users\ecerulm\Downloads\apache-openjpa-1.2.1-binary\apache-openjpa-1.2.1\lib" includes="*.jar"/>
             <!--  or if you create a OpenJPA Library you can use that instead  -->
            <!--<pathelement path="${libs.OpenJPA.classpath}"/>-->
        </path>
 
        <taskdef name="openjpac" classname="org.apache.openjpa.ant.PCEnhancerTask">
            <classpath refid="openjpa.path.id"/>
        </taskdef>
 
 
        <openjpac>            
            <classpath refid="openjpa.path.id"/>
        </openjpac>
        <echo message="end openJPAC"/>
    </target>
 
</project>

You can refer to the OpenJPA jars by either a <fileset> with the file path to the OpenJPA directory or by refererring to a Netbeans Library instead. You can create a OpenJPA Library via Tools ⇒ Libraries ⇒ New Library and add all the jars to the Library. If you name the library “OpenJPA” then you can refer to its classpath with <pathelement path="${libs.OpenJPA.classpath}"/>. See the commented code in the build.xml above.

IMPORTANT: You may be tempted to put the <path> and the <taskdef> outside the <target>. I strongly disencorage this. If you do so then you need to ensure that ./build/classes directory is there before <path> is evaluated otherwise openjpac will fail to locate the META-INF/persistence.xml. So when you do an ant clean, the build/classes is deleted. If you do a ant jar after the ant clean, the build/classes will not be picked up by path and it will fail with a

1
2
3
4
5
6
7
8
9
10
11
 [openjpac] <openjpa-1.2.1-r752877:753278 fatal user error> org.apache.openjpa.u
til.MetaDataException: MetaDataFactory could not be configured (conf.newMetaData
FactoryInstance() returned null). This might mean that no configuration properti
es were found. Ensure that you have a META-INF/persistence.xml file, that it is
available in your classpath, or that the properties file you are using for confi
guration is available. If you are using Ant, please see the <properties> or <pro
pertiesFile> attributes of the task's nested <config> element. This can also occ
ur if your OpenJPA distribution jars are corrupt, or if your security policy is
overly strict.
 [openjpac]     at org.apache.openjpa.meta.MetaDataRepository.initializeMetaData
Factory(MetaDataRepository.java:1567)

Although you can ensure that build/classes is always there overriding -post-clean and creating it there with something like:

<target name="-post-clean">
        <mkdir dir="${build.classes.dir}"/>
</target>

Then you will fall into a second problem: ${build.classes.dir} variable is not accesible outside the <target>. That variable is loaded through -init-project target. So you will be forced to use something like ./build/classes instead of a proper ${build.classes.dir}.So it’s better to define the task inside the target.

By the way, if you don’t set properly the classpath you will probably get an exception like this

java.lang.IllegalArgumentException: java.lang.ClassNotFoundException: com.rubenlaguna.jpaentities.Notes
        at serp.util.Strings.toClass(Strings.java:164)
        at serp.util.Strings.toClass(Strings.java:108)
        at serp.bytecode.BCClass.getType(BCClass.java:566)
        at org.apache.openjpa.enhance.PCEnhancer.<init>(PCEnhancer.java:249)
        at org.apache.openjpa.enhance.PCEnhancer.run(PCEnhancer.java:4493)
        at org.apache.openjpa.ant.PCEnhancerTask.executeOn(PCEnhancerTask.java:89)
        at org.apache.openjpa.lib.ant.AbstractTask.execute(AbstractTask.java:172)
        at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
        at sun.reflect.GeneratedMethodAccessor75.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
        at org.apache.tools.ant.Task.perform(Task.java:348)
        at org.apache.tools.ant.Target.execute(Target.java:357)
        at org.apache.tools.ant.Target.performTasks(Target.java:385)
        at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
        at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
        at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
        at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
        at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:278)
        at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:497)
        at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:151)
java.lang.IllegalArgumentException: java.lang.ClassNotFoundException: com.rubenlaguna.jpaentities.Notes
        at serp.util.Strings.toClass(Strings.java:164)
        at serp.util.Strings.toClass(Strings.java:108)
        at serp.bytecode.BCClass.getType(BCClass.java:566)
        at org.apache.openjpa.enhance.PCEnhancer.<init>(PCEnhancer.java:249)
        at org.apache.openjpa.enhance.PCEnhancer.run(PCEnhancer.java:4493)
        at org.apache.openjpa.ant.PCEnhancerTask.executeOn(PCEnhancerTask.java:89)
        at org.apache.openjpa.lib.ant.AbstractTask.execute(AbstractTask.java:172)
        at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
        at sun.reflect.GeneratedMethodAccessor75.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
        at org.apache.tools.ant.Task.perform(Task.java:348)
        at org.apache.tools.ant.Target.execute(Target.java:357)
        at org.apache.tools.ant.Target.performTasks(Target.java:385)
        at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
        at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
        at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
        at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
        at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:278)
        at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:497)
        at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:151)

References:

Derby 10.5 “OFFSET/FETCH” and JPA

It seems that no current JPA implementation is able to paginate the result using Apache Derby 10.5 “OFFSET/FETCH” mechanism. So javax.persistence.Query setFirstResult and setMaxResults don’t really translate into proper pagination with “OFFSET/FETCH”

STaX: OutOfMemoryError when parsing big files

Java 6 includes STaX , when I tried to parse a Evernote backup file with it, I got a “OOME” error.

java.lang.OutOfMemoryError: Java heap space
     at com.sun.org.apache.xerces.internal.util.XMLStringBuffer.append(XMLStringBuffer.java:205)
     at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.refresh(XMLDocumentScannerImpl.java:1520)
     at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.invokeListeners(XMLEntityScanner.java:2070)
     at com.sun.org.apache.xerces.internal.impl.XMLEntityScanner.peekChar(XMLEntityScanner.java:486)
     at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2679)
     at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
     at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
     at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:548)
     at

Googling a bit I found a bug report 6536111. It says that this should be fixed in 1.6.0_14. But I tried Sun 1.6.0_16 and no luck. I got the exact same thing.

By the way I get this error in both Windows Vista and Mac OS X 10.5.6.

So I decided to go and use WoodStox instead (which is also a STaX API implementation). I worked like a charm.

At the beginning I though I would need to put the woodstox jars in the endorsed dir (-Djava.endorsed.dirs=”xxx”) but actually it’s not necessary at all.

You just put the woodstox´s jars (stax2-api-3.0.1.jar,woodstox-core-lgpl-4.0.5.jar) in the classpath and that´s it. In my case I was using it in a Netbeans Platform Application (RCP) so I created a Netbeans Library Wrapper with the two jars in it and make my module depend on this new library wrapper.

            <class-path-extension>
                <runtime-relative-path>ext/woodstox-core-lgpl-4.0.5.jar</runtime-relative-path>
                <binary-origin>release/modules/ext/woodstox-core-lgpl-4.0.5.jar</binary-origin>
            </class-path-extension>
 
            <class-path-extension>
                <runtime-relative-path>ext/stax2-api-3.0.1.jar</runtime-relative-path>
                <binary-origin>release/modules/ext/stax2-api-3.0.1.jar</binary-origin>
            </class-path-extension>

The JARs use the Service Provider (SPI) feature of jar files to register themselves as an STaX implementation. No changes in the code, you still use the STaX interface to do the parsing but the WoodStox implementation will be used instead.

...
...
                in = new FileInputStream(toAdd);
                XMLInputFactory factory = XMLInputFactory.newInstance();
                factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
                XMLStreamReader parser = factory.createXMLStreamReader(in);
                int inHeader=0;
                for (int event = parser.next();
                        event != XMLStreamConstants.END_DOCUMENT;
                        event = parser.next()) {
                    switch (event) {
                        case XMLStreamConstants.START_ELEMENT:
                            if ("title".equals(parser.getLocalName())) {
                                inHeader++;
                            }
                            ....
                            ....
                            ....

JTable, Beans Binding and JPA pagination

In my previous post I talk about JTable and JPA pagination through a custom TableModel.

Now working directly with TableModel is not want you want to do, you want to use Beans Bindings because it means less manual coding and a lot of help from the IDE (like Netbeans).

With netbeans you can easily bind a JTable to the result list of JPA query. But if that Query returns thousands of rows it’s going to be slow or unfeasible. And if you try to use JPA pagination (with Query.setMaxResults()) then you end with a table that will only show a subset of the rows.

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.

The “trick” here is to avoid binding the Table to the the result list given by the Query.getResultList(). You can create a custom List that does the JPA pagination behind the curtains and bind the JTable to that List instead.

How is this different from doing a custom TableModel? custom TableModel, custom List sound like the same amount of work. Well, right is the same amount of work but if you use Beans Bindings you get a lot of help from the IDE to manipulate the JTable graphically, etc.

You can follow any of the existing tutorials to create JTables bound to JPA entities to get an idea of how Beans Binding work.

Now I’m going to modify the test aplication from my previous post to use Beans Bindings together with the JPA pagination.

I’m assuming that the Entity class Customers from the previous post is already there, and TopLink and derby jars are in the classpath.

Here are the steps to create a JTable bound via Beans Binding to a List backed by a JPA Query:

Right-click on the project New ⇒ JFrame Form

JFrame Form wizard

Add the Table from the Palette to the JFrame

Adding a Table to the frame

Now we can add the EntityManager and the Query. Instead of adding those manually by typing we can add them graphically. Right-click on the Other Components item on the Inspector Window and selecting Add from Palette ⇒ Java Persistence ⇒ Entity Manager

inspector window

Now we can configure the EntityManager by selecting it in the Inspector window and changing the properties in the Properties windows.
entitymanager properties

In this case we change the persistenceUnit to “JTablePaginationJPAPU” .

Then we can add the Query to the form. Inspector ⇒ Other Components ⇒ Add from Palette ⇒ Java Persistence ⇒ Query

And then we configure the query by changing its name to getRowsQuery and changing the query property to “SELECT c FROM Customers c” and the entityManager to “entityManager1″:

query properties

Add a second query to the form to get the number of rows in the table. Call it getRowCount and set the entityManager to “entityManager1″ and the query to “SELECT COUNT(c) FROM Customer c

inspector2

getRowCount

Now we need a Query List because that is what we will bind to the JTable. Again Inspector ⇒ Other Components ⇒ Add to Palette ⇒ Java Persistence ⇒ Query Result.

We could link the Query Result to the Query but we won’t do that because then we don’t get pagination. What we will do with the query result is to change the “Custom Creation Code” property to “getList()” a method call that we will implement later. We also change the “Type Parameters” property to <Customers> to let the IDE know the type of objects stored in the list so netbeans is able to make suggestions later when we bind the JTable to this list.

query result properties

Now we add the getList() method to our class

    private List<Customers> getList() {
        List<Customers> toReturn = new ResultListJPA<Customers>(rowCountQuery, getRowsQuery);
        return toReturn;
    }

You can create ResultListJPA class in the same file:

class ResultListJPA<T> extends AbstractList<T> implements List<T> {
 
    private final Query rowCountQuery;
    private final Query getRowsQuery;
    private int startPosition;
    private int counter=0;
    private List<T> cache = null;
 
    ResultListJPA(Query rowCountQuery, Query getRowsQuery) {
        this.rowCountQuery = rowCountQuery;
        this.getRowsQuery = getRowsQuery;
        this.startPosition = 0;
        this.cache = getItems(startPosition, startPosition + 100);
    }
 
    public int size() {
        return ((Long) rowCountQuery.getSingleResult()).intValue();
    }
 
 
    public T get(int rowIndex) {
        if ((rowIndex >= startPosition) && (rowIndex < (startPosition + 100))) {
        } else {
            this.cache = getItems(rowIndex, rowIndex + 100);
            this.startPosition = rowIndex;
        }
        T c = cache.get(rowIndex - startPosition);
 
        return c;
    }
 
    private List<T> getItems(int from, int to) {
        System.out.println("numer of requests to the database " + counter++);
        Query query = getRowsQuery.setMaxResults(to - from).setFirstResult(from);
 
        //add the cache
        List<T> resultList = query.getResultList();
        return resultList;
    }
}

OK, now we’ll bind the result list object with the JTable. Right-click on the JTable and select Table Contents ⇒ Bound ⇒ Binding Source ⇒ list1 . list1 is the name of the ResultListJPA object in my case.
table binding

Now click on the Columns tab and Insert 3 new columns. Select the first one and change the Title to “Id Number” and select “id” in the expression combo box (it should appear as ${id}).

Do the same thing for the other 2 columns until you get something like this
Table binding

Now the JTable is properly bound to the list and we can run the file. You can see in the screenshot that the JTable shows the contents of the database and it makes new queries to the database as you scroll through the JTable.

final

The source code is here