JPA 2 and Netbeans Guide - Part 1 - Getting Started
This is the first part of a series of posts about JPA 2 and Netbeans 6. This series has the goal to show up how to get started with JPA 2, as well as creating complex model using relationship and inheritance.
This part one is going to show up the steps to create your first application that access the database using JPA 2 (Stand alone application). Using Netbeans 6, this process is easy and takes less than five minutes.
Requirement
- Understand JPA concepts - If you have no idea what JPA is, please google it first
- Netbeans 6.8 and glassfish v3 installed
- MySQL database installed - If you have another one, make sure you have the JDBC driver
Preparing the database
Before we get started with Netbeans, let’s prepare our database. The instructions below are regarding MySQL, but if you’re using another database, you may need to change the scripts to work out.
Firstly, connect to your database:
mysql -u root -p
Then, create the database and select it. Let’s call it as “jpatutorial”
create database jpatutorial; use jpatutorial;
Now, run the script below. Basically it creates a table called “products” and insert three products by default.
create table products (id int not null auto_increment, description varchar(40), price double, primary key(id)); insert into products (description, price) values ('product 1',100); insert into products (description, price) values ('product 2',200); insert into products (description, price) values ('product 3',200.50);
Creating the project within Netbeans
Now the “magic” starts. Open up Netbeans and create a simple Java program called “JPAExample01″. Netbeans also creates a “Main” class for you.

Creating the Model and persistence.xml
After the project is created, right mouse click on it and go to New -> Other -> Persistence -> Entity Classes from Database. On next screen, select Database Connection -> New Database Connection and type the information from your database. After that, the table “products” should appear on the screen.

Select “products” and click on “Add” and then “Next”.
On third screen, you must create our “Persistence Unit”. Click on Create Persistence Unit… button. Now, we must select the provider we want. By default, Netbeans brings the EclipseLink, but you’re free to change it. Also, you can change the Unit name and table generation strategy, but let’s keep the default so far.

The persistence.xml file has created, now click next until the end and finish the process (you can accept all the default options).
Take a look at the Project and you’re gonna see a new folder called “META-INF” with the file persistence.xml and the file “Products.java” created.
Examining the Products.java
Usually a model is a simple POJO. With JPA, the POJO has annotations that define the primary key, columns, relationship and so on. Netbeans has already done these annotations for us. Open the Products.java and have a look.
@Entity @Table(name = "products") @NamedQueries({ @NamedQuery(name = "Products.findAll", query = "SELECT p FROM Products p"), @NamedQuery(name = "Products.findById", query = "SELECT p FROM Products p WHERE p.id = :id"), @NamedQuery(name = "Products.findByDescription", query = "SELECT p FROM Products p WHERE p.description = :description"), @NamedQuery(name = "Products.findByPrice", query = "SELECT p FROM Products p WHERE p.price = :price")}) public class Products implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Column(name = "description") private String description; @Column(name = "price") private Double price;
Attention: The netbeans has already generated some NamedQueries for us too, Thanks Netbeans team
Running and testing the JPA
To test JPA, we must a EntityManager. In a stand-alone application, to get it, we must a EntityManagerFactory. Let’s change our Main class and initialize a EntityManager and call a simple NamedQuery. The Main class looks like:
package jpaexample01; import entities.Products; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class Main { public static void main(String[] args) { EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("JPAExample01PU"); EntityManager em = emFactory.createEntityManager(); List<Products> listProducts = em.createNamedQuery("Products.findAll").getResultList(); for (Products product : listProducts) { System.out.println("Product: " + product.getDescription()); System.out.println("Price: " + product.getPrice()); System.out.println("---------------------------------------"); } } }
Pay attention on main method. We get a EntityManagerFactory, then an EntityManager, we call a NamedQuery already done and finally we iterate over the list and print out the description and price of the product.
Before run the code, you must add the JDBC driver into the project’s classpath. To do that right mouse click on the project Properties -> Libraries -> Add Library -> MySQL JDBC Driver
Now you can run the application and if everything is fine, you are gonna see in the console:
Product: product 1 Price: 100.0 --------------------------------------- Product: product 2 Price: 200.0 --------------------------------------- Product: product 3 Price: 200.5 ---------------------------------------
Conclusion
As you can see, Netbeans has a great support for JPA 2. You were able to create your first application in few minutes.
This post finishes here, in the next one we are going to talk about JPA 2 in a web environment. You’re gonna see the code is similar, but the way to obtain the EntityManager is different.
If you have any comment or question about this post, fell free to leave your message below.

Brazilian guy, IT Specialist, Linux User, IBM Certified SOA Fundamentals, Rational Developer, Sun Certified Java Associate 1.0, Sun Certified Java Programmer 1.4, Sun Certified Web Component Developer 1.4 and Sun Certified Business Component Developer 5. Also Ruby and Python enthusiastic.
i host 5 of my blogs on Blogspot and it is really good for beginners. but if you want something with more features, nothing beats wordpress-”;
You without doubt have a style all your own when it comes to creating these nice blog posts.