Simple JPA Application with Netbeans
March 6, 2008 47 Comments
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 Person.java. 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 Person.java 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 Demo.java
</p></p>
<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");
p.setPhoneNumber("+6281390989669");
Demo demo = new Demo();
demo.persist(p);
}
public void persist(Object object) {
EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("simple-jpaPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try {
em.persist(object);
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
} finally {
em.close();
}
}
}
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.









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
JSP>Servlet>SessionBeans>JPA.
please send me on abishek_indian@yahoo.com
Iam really looking for something like that, Iam trying to run, but no success yet hope i could do soon..
thanks
abishek kumar.
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
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..!
http://www.roseindia.net/ejb/entity-bean-example.shtml
please help me if you can..! thanks
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.
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.
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
Hallo chester
salam kenal juga..
aku pikir yang lain hanya pada bengong semua hehehehe…
wah ternyata JaMu kemarin ada manfaatnya juga ya.. mantap deh
kembali ke pertanyaan kamu
aku lagi buat tulisan tentang itu bentar malam aku post.. i hope soo
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 :
http://vyor.wordpress.com/2008/02/20/akses-web-service-net-dengan-java-swing/
disitu ada contoh sederhana untuk menampilkan data ke tabel
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();
++i;
}
tMhs.setModel(new DefaultTableModel(data,
new String[]{“NIM”,”Nama”,”Alamat”}));
semoga membantu !
Salam,
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.
Mas bisa minta tutorial netbeans yang utk bkin program aplikasi HP
ya klo bs yg bhs indo
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
ada contoh gamenya kalo gak salah
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:
oracle.toplink.essentials.PersistenceProvider
oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
Returned null to createEntityManagerFactory.
Any ideas or suggestions?
Hi,
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 (http://wiki.netbeans.org/CommunityDocs).
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.
Thanks,
Varun Nischal
http://nb-community-docs.blogspot.com/
–
“You must do the things you think you cannot do.”
Good article on JPA with NetBeans 6.1 :
JPA NetBeans
minta contoh2 coding spring MVC donk..
yang beginner2 aja..
trims
Mantap Kak !!!!
pak hendro kapan buat tutorial tentang design pattern?
kutunggu-tunggu
Many thanks
I have been banging my head on a wall
ya mas… yang MVC-MVC itu loh….
walaupun DAO termaksud MVC jg kan???
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
mas….kok pinter banget toh mas…..doain aku biar bisa pinter dan manfaatin ilmu kaya mas yah……..
Thank you!!! I had been looking for some help to JPA like this but i could not find it
… simple, clear and effective; thank you again… (sorry about my english, i speak spanish but i’m doing my best hehe)
your welcome Jhoan
good tutorial…oh pake project lombok pada setter dan getternya pasti bagus…! project Lombok di launk.wordpress.com
Very nice tutorial. My question is, how do i use named queries to update or get the records from the database
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 ??
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!!
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.
mas,aq mo bikin laporan bulanan pake jsp, tapi format tglnya inggris,gmana ngrubah biar bisa jg “tanggal bulan tahun”…???
tolongin donk
@ichsan: pake jstl format date
Hey,
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…
bedanya ORM activeobject sama JPA apa ya? mohon penjelasannya.. makasih
read this http://www.javalobby.org/articles/activeobjects/
Finally!
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.
hope it useful for you
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.
Thx.
Hi,
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…
Thx.
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:
org.eclipse.persistence.jpa.PersistenceProvider
entity.Person
Run the Demo class now and your table and data would be created. Peace!
hai/……………….salam kenal
nice work….
gimana cara download.nya???????????
apanya yang didownload?
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?