Developers, Developers, Developers! Maksim Sorokin IT Blog


JPA Persistence With GlassFish

So you want to use javax.persistence. Here is how you can configure it and run with GlassFish.

In this example we will use MySQL database.
First, we will need to configure GlassFish JDBC resources. In GlassFish administration portal go to "Resources->JDBC->Connection Pools". Create new Connection Pool with name examplePool. Set Resource Type to java.sql.Driver; Database Vendor to MySql, com.mysql.jdbc.Driver.
Then go to "Resources->JDBC->JDBC Resources". Add new resource with JNDI Name jdbc/example. Set Pool Name to examplePool.

In the application under src/main/resource META-INF folder should be created. And inside META-INF folder persistence.xml file added with following content:

<?xml version="1.0" encoding="UTF-8"?>
    <persistence xmlns="" xmlns:xsi=""
  <persistence-unit name="default" transaction-type="JTA">

Where ${jtaDataSource} should be jdbc/example. Or you can enable filtering in Maven pom.xml file and specify jdbc/example there So afterwards it would be easier to change and maintain it:


You are ready to go! Create Entity:

@Table(name = "pencils")
public class Pencil {
  private int id;

  private String color;

  public int getId() {
    return id;

  public String getColor() {
    return color;

Inject javax.persistence.PersistenceContext:

private EntityManager em;

And you can create queries:

Query q = em.createQuery("select p from Pencil p where p.color=:color");
q.setParameter("color", "blue");
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.