Developers, Developers, Developers! Maksim Sorokin IT Blog

26Feb/10Off

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="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
  <persistence-unit name="default" transaction-type="JTA">
    <jta-data-source><strong>${jtaDataSource}</strong></jta-data-source>
  </persistence-unit>
</persistence>

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:

<build>
  ...
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
  ...
</build>
...
<properties>
  <jtaDataSource>jdbc/example</jtaDataSource>
</properties>

You are ready to go! Create Entity:

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

  @Column
  private String color;

  public int getId() {
    return id;
  }

  public String getColor() {
    return color;
  }
}

Inject javax.persistence.PersistenceContext:

@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.