mardi 2 mars 2010

JavaFX and the Databases with JPA 2.0

In the first part, we have seen how to access data with JPA. In this second part we are going to see how to get data from database with JPA 2.0 and to display them with JavaFX.


To do that we will re-use the table and the entity created in the part one, and we will create a Java class which contains the code to execute the JPA requests.
Let’s go and create the Java class.
The Java class contains one constructor to create the EntityManager and 2 methods:
findAll():
This method gets all the records from the table and uses the namedQuery findAllAlbum

getArtisteNameBeginningBy(String begining):
This method get all the records from the table where the field artisteName begin by the parameter
"begining"
For this second method, I use criteria API just because I wanted to test it…
Normally in this case, we don’t have to use criteria API because we don’t need to create dynamically a query and the criteria API was created to build dynamically and safely a query (without to concatenate strings to build a jpql request, like in JPA 1.0).
The best way to do that, is to use directly a jpql request like this


Query query = em.createQuery("select m from Music m where m.artisteName like :param");
query.setParameter("param", param);
List<Music> musics = query.getResultList();

Or, if you want, create another namedQuery in the Entity

@NamedQueries({
   @NamedQuery(name = "findAllAlbum", query= "select m from Music m"),
   @NamedQuery(name = "findAllAlbumWhereArtisteLike",query="select m from Music m where m.artisteName like :param")
})

And call it like that

Query  query = em.createNamedQuery("findAllAlbumWhereArtisteLike");
query.setParameter("param", param);
List<Music> musics = query.getResultList();

We will not use this method in this part but in the last part.

MusicServices.java
package paddy.service;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import paddy.domain.Music;

/**
 *
 * @author Patrick
 */
public class MusicServices {

    EntityManagerFactory emf;
    EntityManager em;

    public MusicServices(){
        emf = Persistence.createEntityManagerFactory("MusicAndLight");
        em = emf.createEntityManager();
    }

    public List<Music> findAll(){

        Query  query = em.createNamedQuery("findAllAlbum");
        List<Music> musics = query.getResultList();

        return musics;
    }

    public List<Music> getArtisteNameBeginningBy(String begining){

        String param = begining+"%";

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Music> query = cb.createQuery(Music.class);
        
        Root<Music> music = query.from(Music.class);
        query.where(cb.like(music.<String>get("artisteName"), param));
        List<Music> musics = em.createQuery(query).getResultList();

        return musics;
    }

    @Override
    protected void finalize() throws Throwable {
        try {
            em.close();
            emf.close();
        } finally {
            super.finalize();
        }
    }
}

Now, let’s call this class from javaFX to get the data from the database and to display them in JavaFX

Main.fx
package javafxjpa2basic;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.Button;
import paddy.domain.Music;
import paddy.service.MusicServices;

/**
 * @author Patrick
 */

var listMusic;
var seqMusic:Music[];

var musicServices:MusicServices = MusicServices{};

Stage {
    title: "Application title"
    scene: Scene {
        width: 600
        height: 175
        content: [
            Button {
                text: "Find all the musics"
                action: function() {
                        delete seqMusic;

                        listMusic = musicServices.findAll();
                        seqMusic = listMusic.toArray(seqMusic);                        

                        println("seqMusic: {seqMusic} ");
                }
            }
            ListView {
                layoutY : 50
                 width: 575
                 height : 100
                 items: bind seqMusic
            }
        ]
    }
}
 
The key points :
  •  Creating an instance of the Java class in JavaFX
    var musicServices:MusicServices = MusicServices{};
  • Calling the findAll method
    listMusic = musicServices.findAll();
  • Converting the java list to a JavaFX sequence
    seqMusic = listMusic.toArray(seqMusic);
  • Binding the sequence to the JavaFX GUI List
    items: bind seqMusic
Note: don’t forget to create (in NetBeans) a library containing the jar DerbyClient.jar and being called DerbyClient.

1 commentaire:

Sergey Surikov a dit…

see exemple of JavaFX + JavaDB - http://blogs.sun.com/FrancoisOrsini/entry/javafx_and_java_db_apache