JPA Using NetBeans and MySQL

JPA Using NetBeans and MySQL

Submitted by Dmitry Boychev on Mon, 12/01/2014 - 00:27
Java persistence

In this article you will learn how to quickly get started with JPA. I will be using NetBeans and MySQL database to store data using JPA. If you have MySQL running, all you have to do is follow the steps below.

First let’s create a database that we will be using later on. From the command line you can just run the following command. Note, I will be using “JPA” as the name of my database for this tutorial.

create database JPA;

Now we are ready to fire up NetBeans and get started. Once NetBeans is loaded, created a new “Java Application” project and give it a name. In my case I named it “JPA”. Go ahead and delete the generated java class file, we will create our own.

[[{"type":"media","view_mode":"media_large","fid":"158","attributes":{"alt":"","class":"media-image","height":"331","width":"480"}}]]

[[{"type":"media","view_mode":"media_large","fid":"159","attributes":{"alt":"","class":"media-image","height":"331","width":"480"}}]]

Now, right click on the (in my case) “JPA” package, select new, other, persistence, Entity Class as shown in the picture below.

[[{"type":"media","view_mode":"media_large","fid":"160","attributes":{"alt":"","class":"media-image","height":"331","width":"480"}}]]
 
If you do not see “Persistence” from the categories, then you will need to download the plugin. To do that, click on Tools>Plugins, then go to available plugins tab and search for “persistence”, select and install it as shown in the picture below. If you have persistence installed then skip to the next step.
 

[[{"type":"media","view_mode":"media_large","fid":"161","attributes":{"alt":"","class":"media-image","height":"299","width":"480"}}]]

Give new entity class a name, in my case I left it as the default name the IDE provided “NewEntity”. Click next and from database connection select “new database connection” and look for MySQL as shown in the picture below.

[[{"type":"media","view_mode":"media_large","fid":"162","attributes":{"alt":"","class":"media-image","height":"358","width":"480"}}]]

Click next, and a configuration window should show up for setting up the connection to the MySQL database. In my case the database is running on a remote server but I have HeidiSQL connected through SSH tunnel on local port 3307. So I used the following configurations.

[[{"type":"media","view_mode":"media_large","fid":"163","attributes":{"alt":"","class":"media-image","height":"239","width":"480"}}]]
 

And here is a screenshot of my HeidiSQL connection in case you want to set up a similar environment.

[[{"type":"media","view_mode":"media_large","fid":"164","attributes":{"alt":"","class":"media-image","height":"287","width":"480"}}]]
 
Once you have successfully configured a connection to the database, click finish and the IDE will generate the NewEntity class with some code. We will create a column “Name” type varchar, length 100 in this code and delete some unnecessary stuff. Here is the finished result:
package jpa;

import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class NewEntity implements Serializable {
  private static final long serialVersionUID = 1L;
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO) private Long id;
  @Column(length = 100)
  private String name;

  public String getName() {
   return name;
  } 
  public void setName(String name) { 
    this.name = name; 
  } 
  public Long getId() { 
    return id; 
  }
  public void setId(Long id) { 
    this.id = id; 
  } 

  @Override public int hashCode() {
    int hash = 7; 
    hash = 59 * hash + Objects.hashCode(this.id); 
    hash = 59 * hash + Objects.hashCode(this.name); 
    return hash; 
  } 
  @Override public boolean equals(Object obj) {
    if (obj == null) {
     return false; 
    } 
    if (getClass() != obj.getClass()) { 
      return false; 
    } 
  final NewEntity other = (NewEntity) obj;
    if (!Objects.equals(this.id, other.id)) { 
      return false; 
    } 
    if (!Objects.equals(this.name, other.name)) {
     return false;
    } 
    return true; 
  } 
  @Override public String toString() {
    return "jpa.NewEntity[ id=" + id + " ]"; 
  } 
}

Now we will create a JPA Controller. To do that, right click on the “jpa” package > other again and choose Persistence>Jpa Controller Classes from Entity Classes this time. The IDE should generate the following code:

package jpa;
 
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import jpa.exceptions.NonexistentEntityException;
 
public class NewEntityJpaController implements Serializable {
 
public NewEntityJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
 
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
 
public void create(NewEntity newEntity) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(newEntity);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
 
public void edit(NewEntity newEntity) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
newEntity = em.merge(newEntity);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Long id = newEntity.getId();
if (findNewEntity(id) == null) {
throw new NonexistentEntityException("The newEntity with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
 
public void destroy(Long id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
NewEntity newEntity;
try {
newEntity = em.getReference(NewEntity.class, id);
newEntity.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The newEntity with id " + id + " no longer exists.", enfe);
}
em.remove(newEntity);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
 
public List<NewEntity> findNewEntityEntities() {
return findNewEntityEntities(true, -1, -1);
}
 
public List<NewEntity> (int maxResults, int firstResult) {
return findNewEntityEntities(false, maxResults, firstResult);
}
 
private List<NewEntity> (boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(NewEntity.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
 
public NewEntity findNewEntity(Long id) {
EntityManager em = getEntityManager();
try {
return em.find(NewEntity.class, id);
} finally {
em.close();
}
}
 
public int getNewEntityCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<NewEntity> rt = cq.from(NewEntity.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
Now we will create a new package named App and create an Application.java class in that package. To do that, right click on project “JPA”, select New>Java Package. Give it a name, in my case it is “App”. Now right click on the package “App” and create a new Java class named Application in my case.

In this class we will create our entityManagerFactory and set a name to the column we created with the @Column annotation in NewEntity.java class. Here is the code:

package App;
 
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import jpa.NewEntity;
import jpa.NewEntityJpaController;
 
public class Application {
public static void main (String args[]) {
EntityManagerFactory objFactory = Persistence.createEntityManagerFactory("JPAPU");
EntityManager manager = objFactory.createEntityManager();
NewEntity record = new NewEntity();
NewEntityJpaController jpa = new NewEntityJpaController(objFactory);
List<NewEntity> list = jpa.findNewEntityEntities();
 
record.setName("Test");
 
jpa.create(record);
 
for (NewEntity l : list) {
System.out.println("Cod.: "+l.getId()+"\nName.: "+l.getName());
 }
}
}

Make sure the persistence-unit name from the persistence.xml file is what you are using in line 12. EntityManagerFactory objFactory = Persistence.createEntityManagerFactory("JPAPU");

Here is how it looks in persistence.xml:  <persistence-unit name="JPAPU" transaction-type="RESOURCE_LOCAL">

Now you are ready to run the project and see that it created a table NewEntity in JPA database and a column “name” with the word “test” in it or whatever you have put in the code. Here is a screenshot of my database after I ran the code.

[[{"type":"media","view_mode":"media_large","fid":"165","attributes":{"alt":"","class":"media-image","height":"255","width":"480"}}]]