Simple JPA Application with Netbeans

Well yesterday I was demo about JPA (Java Persistent API) with Netbeans. How easy to develop simple database application using JPA with Netbeans IDE.

JPA introduction please refer to Sun Microsystem site

Ok! here the step by step about the sample application

Create a database in your database engine. For example dbperson. I’m using Mysql as the database.

Open you Netbeans IDE and try to connect to the database. Please read my other writing about “Manipulasi MySQL dengan Netbeans


Our database doesn’t have any tables. JPA will create it automatically for us. Next step we create a new Java Project in Netbeans, simple-jpa for example.


Then add mysql connector to the project. Right click on Libraries–>Add Library. Find libarary MySQL JDBC Driver.



Next step we create an Entity class Right click on Source Package New–>Entity Class


Write Person for the Class Name and entity for the Package.


Click on the Create Persistence Unit… button and chose Database Connection to the dbperson.


Click on Create button and click Finish. Add more property on for example we have name, address and phone number.


And don’t forget to add setter and getter method for that new attribute. Ok next step we create another class

<p align="left">import entity.Person;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
public class Demo {
public static void main(String args[]){
Person p = new Person();
p.setName("Hendro Steven");
p.setAddress("Salatiga, Indonesia");

Demo demo = new Demo();

public void persist(Object object) {
EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("simple-jpaPU");
EntityManager em = emf.createEntityManager();
try {
} catch (Exception e) {
} finally {

Ok now build your project and run the Demo class… and the magic will show🙂 JPA will create your table automatically and insert our object to the table🙂 without any sql that we create.



56 Responses to Simple JPA Application with Netbeans

  1. Hi Steven,

    I am new to EJB3 , your blog helped me to understand how to develop JPA, thanks for it. it was easy to understand.

    one more thing if you have wrote any blog or if you find any blog on developing sample EJB project with complete cyce
    please send me on

    Iam really looking for something like that, Iam trying to run, but no success yet hope i could do soon..
    abishek kumar.

  2. Hendro Steven says:

    hallo Abishek Kumar,
    Thanks for your comment..
    wait for 1 or 2 days I’ll write a complete JEE step by step tutorial with Netbeans. I’ll show you how easy to develop struts/jsp/servlet>sessionbean>jpa application.

    happy code😀

  3. thanks man, i will be waiting for your blog.. plz do reply me when you are done..!
    If you know please tell me answer for this..!

    when we run any enterprise application on netbeans ide and glassfish server do we need to deploy any thing on glass fish..?
    I mean is there any file like jboss-app.xml of Jboss server. I was following this example from this link but not able to run on glass fish..!

    please help me if you can..! thanks

  4. Hendro Steven says:

    mmm.. i’m veryyy buzzzzy.. this week😦 maybe this weekend i’ll post it😀
    glassfish?? you not need to add any library to running enterprise application on it. Of course if you using some library like mysql-connector or jpa hibernate implementation and etc you sould include it in your application library. jbozz-app.xml is for jboss server. It’s a specific configuration for jboss and not for glassfish😀
    Due the example you mention above, it’s for Jboss server. If you plan to deploy it on glassfish using netbeans ide just create the classess and the jsp page and use TopLink as the jpa implementation.

  5. thanks for your clarrification. I really appretiate for your prompt replies.. it is nice.. !
    will be waiting for your new blogs.!

    good luck to you.

    abishek kumar.

  6. chester says:

    hai mas steven, salam kenal. Saya kemarin ikut JAMU dan merasa tertarik dengan tip yang dipaparkan kemarin itu. Saya sudah mencobanya dan berhasil. Tapi saya merasa kesulitan bagaimana caranya untuk menampilkan data, misalnya ke dalam tabel. juga bagaimana caranya untuk mengupdate data dengan menggunakan klausa where xxx, trims

  7. Hendro Steven says:

    Hallo chester😀 salam kenal juga..
    wah ternyata JaMu kemarin ada manfaatnya juga ya.. mantap deh🙂 aku pikir yang lain hanya pada bengong semua hehehehe…

    kembali ke pertanyaan kamu😀
    aku lagi buat tulisan tentang itu bentar malam aku post.. i hope soo😦

  8. vyor says:

    to : Chester

    Ini saya sedikit share tentang menampilkan data kedalam tabel. Saya asumsikan data yang dikembalikan dari DAO kita berupa List Of Mahasiswa. Objek mahasiswa diasumsikan field-fieldnya adalah NIM,Nama,Alamat.
    Saya contohkan nama Listnya adalah “listMhs” dan nama tabel “tMhs”.

    Contoh coding bisa kamu liat disini :

    disitu ada contoh sederhana untuk menampilkan data ke tabel

  9. vyor says:

    Bagian penting dari coding tersebut sebernya pada perulangannya.

    Jika kita menggunakan asumsi tadi maka codingnya dapat kita rubah menjadi :

    String[][] data = new String[listMhs][3];
    int i = 0;

    for(Mahasiswa m : listMhs){
    data[i][0] = m.getNIM();
    data[i][1] = m.getNama();
    data[i][2] = m.getAlamat();

    tMhs.setModel(new DefaultTableModel(data,
    new String[]{“NIM”,”Nama”,”Alamat”}));

    semoga membantu !


  10. shinobi says:

    pak, update primary key di toplink koq ga bsa ya? errornya spt ini :

    The attribute [npm] of class [Mahasiswa.npm] is mapped to a primary key column in the database. Updates are not allowed.

  11. dodo says:

    Mas bisa minta tutorial netbeans yang utk bkin program aplikasi HP

  12. dodo says:

    ya klo bs yg bhs indo

  13. Hendro Steven says:

    Hallo Dodo..
    wah maaf kebetulan saya tidak mendalami JME (java untuk HP) tapi kalo mau contohnya sebenarnya udah ada di installasi Netbeans untuk JME. Coba aja create project baru tapi pilih Sample pasti ada deh🙂

  14. Hendro Steven says:

    ada contoh gamenya kalo gak salah😀

  15. Jim says:

    I tried your example but I got the following errors in netbeans 6.1

    Jul 23, 2008 5:54:38 PM org.jdesktop.application.Application$1 run
    SEVERE: Application class com.dgtlrift.test.Test failed to launch
    javax.persistence.PersistenceException: No Persistence provider for EntityManager named simple-jpaPU: The following providers:
    Returned null to createEntityManagerFactory.

    Any ideas or suggestions?

  16. Varun says:


    My name is Varun Nischal and I’m the NetBeans Community Docs Contribution Coordinator. Your blog entry would make a fantastic tutorial for our Community Docs wiki (

    Would you be willing to contribute it? If you need any help or have any questions, please contact me at nvarun AT netbeans DOT org

    I look forward to hearing from you.

    Varun Nischal

    “You must do the things you think you cannot do.”

  17. Krishna says:

    Good article on JPA with NetBeans 6.1 :
    JPA NetBeans

  18. Fery says:

    minta contoh2 coding spring MVC donk..

    yang beginner2 aja..


  19. vyor says:

    Mantap Kak !!!!

  20. hendra says:

    pak hendro kapan buat tutorial tentang design pattern?


  21. FemiF says:

    Many thanks
    I have been banging my head on a wall

  22. silver X says:

    ya mas… yang MVC-MVC itu loh….

    walaupun DAO termaksud MVC jg kan???

  23. Hendro Steven says:

    DAOMVC DAO Berhubungan dengan cara mengakses data sedangkan mvc untuk pemisahan layer model, view dan controller.. Biasanya DAO dipake disisi bagaimana mengakses Model dalam MVC

  24. miftahul says:

    mas….kok pinter banget toh mas…..doain aku biar bisa pinter dan manfaatin ilmu kaya mas yah……..

  25. Deathlock says:

    Thank you!!! I had been looking for some help to JPA like this but i could not find it :D… simple, clear and effective; thank you again… (sorry about my english, i speak spanish but i’m doing my best hehe)

  26. Hendro Steven says:

    your welcome Jhoan🙂

  27. launk says:

    good tutorial…oh pake project lombok pada setter dan getternya pasti bagus…! project Lombok di

  28. Joseph says:

    Very nice tutorial. My question is, how do i use named queries to update or get the records from the database

  29. sms says:

    hey … nice tutorial …
    i m getting one error ……..

    No Persistence provider for EntityManager named SampleJPAPU …
    i have given name for my persistance unit as SampleJPAPU …

    can u help me in this ??

  30. alvarodoune says:

    hola, necesito listar unos movimientos de una tabla, pero el campo de la condicion es foreign de otra tabla, como seria la sentencia?? yo probe esta y no anda. gracias

    public static List MovimientosXsupermercado(String nombre){
    List lista;
    lista = em.createQuery(“Select m from Movimiento m where m.supermercado_nombre=:nom”).setParameter(“nom”, nombre).getResultList();
    return lista;

    explico que supermercado_nombre es una foreign!!

  31. cscsaba says:

    Great tutor It get the taste of Netbeans and JPA.
    Eclispse tutors far cry from this simplicity.

    Thanks it is very helpful and make clear the basics of over mystified subjects.

  32. ichsan says:

    mas,aq mo bikin laporan bulanan pake jsp, tapi format tglnya inggris,gmana ngrubah biar bisa jg “tanggal bulan tahun”…???
    tolongin donk

  33. Hendro Steven says:

    @ichsan: pake jstl format date

  34. mark says:


    i Know that was long time ago but… did you ever finished the complete JEE step by step tutorial with Netbeans? where you were going to explain how to develop struts/jsp/servlet>sessionbean>jpa application…

    I’ve been looking deeply in your blog but i haven’t succed… could you at least point me to some source where i can find some info about it?

    I got lost when all the Indonessian started… I’m sorry!😦

    BTW! Thanks for the simple JPA tutorial…

  35. yoga says:

    bedanya ORM activeobject sama JPA apa ya? mohon penjelasannya.. makasih

  36. jplans says:

    I’ve found the best site on my first JPA.
    Thanks for this tutorial. This is very helpful..
    Thank you very much. I tried many tutorial sites but one of them doesn’t work..
    Finally i found one. GOOD job.

  37. Hendro Steven says:

    hope it useful for you😀

  38. Rugamba Emmanuel says:

    This is a good tutorial Steve. I am not usually using JPA, but I ma going to try your example may be it will help me.

    Is JPA easy to deploy? Can you help me with some steps of doing so; if possible, mention a really good DBMS that can be used with it and easy to deploy.

    I asked you this because I tried many times by using Mysql, sqlite3, JavaDB, Ms Access, but always the problem is that whenever I take away the jar file to other computers, it can’t work. It needs to install the DBMS, while it could be better to be automatically installed. I know your help is useful.


  39. Rohit Gupta says:


    Is there anyone who had really tried and successfully ran this program? Seems everyone, except 2 unfortunates like me, has just read the solution, without really working it out. If one does the steps, one gets an error “No Persistence provider for EntityManager named simple-jpaPU” while running the code. I guess this is somewhat obvious as the code doesn’t show how to define the persistent store simple-jpaPU in the code and arbitrarily uses that in the demo class. I guess this is an incomplete example or something and the persistent xml or something needs to be created to declare this simple-jpaPU persistent unit. I am trying to create a persistent unit in netbeans to see if the code works.

    It’s misleading when the code is not complete… at least for novices like us…


  40. Rohit Gupta says:

    ok, i am able to do this. what additionally needs to be done is to create a persistent unit in netbeans with the name simple-jpaPU. This would create an xml persistent unit. Make sure that the persistent unit xml looks like this:


    Run the Demo class now and your table and data would be created. Peace!

  41. Hendro Steven says:

    🙂 Great Job!!! bravoooo!!!

  42. ade says:

    hai/……………….salam kenal

  43. vhytrhee says:

    gimana cara download.nya???????????

  44. Hendro Steven says:

    apanya yang didownload?

  45. best voip phone for mac says:

    Thank you, I’ve just been searching for info about this topic for a while and yours is the best I have discovered till now. However, what about the bottom line? Are you positive about the source?

  46. aseprojali says:

    mas klo misalnya kita buat si id nya auto increment gmn ?😀

  47. Hendro Steven says:

    Langsung kirim ke printer reportnya

  48. sankar says:

    i have this issue,

    Exception in thread “main” javax.persistence.PersistenceException: No persistence providers available for “jpa4” after trying the following discovered implementations: NONE

    this is my xml file:


    and this is my main method

    import java.util.Date;
    import java.util.List;
    import java.util.Scanner;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;

    public class Test {

    public static void main(String[] args) {

    EntityManagerFactory fac = null;
    EntityManager em = null;

    fac = Persistence.createEntityManagerFactory(“jpa4” );
    em = fac.createEntityManager();

    Sankar b = new Sankar();


    System.out.println(“sucessfully added to the databaseof the book name”+”=”+b.getName());


  49. sankar says:

    my xml file is


  50. Asker! says:

    mas, ada tutorial JPA dengan program desktop netbean yg drag n drop?

  51. I will right away clutch your rss feed as I can’t in finding your e-mail subscription hyperlink or e-newsletter service. Do you have any? Kindly allow me recognize so that I may subscribe. Thanks.

  52. Hendro Steven says:

    blum sempat buat

  53. Hendro Steven says:

    halo sankar, what is your question?

  54. Hendro Steven says:

    fac = Persistence.createEntityManagerFactory(“jpa4″ );
    “jpa4” is your persistence unit name..

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: