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.











Recent Comments