Starting with EJB 3.0 Persistence in Eclipse 3.1 using the GlassFish Reference Implementation

Lucas Jellema 10
0 0
Read Time:10 Minute, 13 Second

This article describes a quick route to starting out with the relatively new EJB 3.0 Persistence API from the Eclipse 3.1 IDE. In a subsequent article, I will discuss the Dali EJB 3.0 Persistence plugin for Eclipse, developed by Oracle, BEA (after taking over SolarMetric) and JBoss.

A lot has been said about EJB 3.0 Persistence. I will not add much to those discussions. It seems to me that the EJB 3.0 Persistence API will prove extremely popular with applications, both running with EJBs in J2EE Containers as well as with Web Applications and even Java Client and stand-alone applications running outside the EJB Container. All major ORM frameworks – including Toplink, Hibernate and Kodo – provide implementations of EJB 3.0 Persistence. So it seems logical that most applications will do their ORM activities through the EJB 3.0 Persistence API, regardless of the implementation they will choose.

In a previous article I have demonstrated how to set up a JDeveloper 10.1.3 environment with the GlassFish reference implementation (actually Toplink Essentials) of EJB 3.0 Persistence:Using GlassFish Reference Implementation of EJB 3.0 Persistence with JDeveloper 10.1.3EA. Before that I discussed getting started with EJB 3.0 Persistence using GlassFish in general:Getting Started with EJB 3.0 Persistence out-of-container using the Reference Implementation (GlassFish). The article you are reading now adds to these two article in discussing the specific set up of Eclipse. Which by the way is very simple.

Let’s assume for the moment that you already have Eclipse 3.1 set up against a JDK 5.0. The steps from here are:

  • Download and install GlassFish (well, mainly download and extract)
  • Start up Eclipse and create a new Java Project
  • Configure the projec
  • Create the Entities, the persistence.xml and the application
  • Run the application, using the proper JVM options

It is not difficult!

Download and Set Up GlassFish

GlassFish can be found at the GlassFish project page
on There is no formal Production Release to be
downloaded. You can find milestones, promoted builds and nightly
builds. It is clear that GlassFish is still very much on the move. For
getting started, you do not need the absolute latest features and you
also do not need production level robustness, so I suggest – as I did –
that you download one of the promoted builds. Click on the Download Now
button and pick the latest promoted build. In my case that was promoted
binary build 1 February 2006 (60Mb).

To install I did the following:

  1. save the downloaded jar file in c:\glassfish
  2. open a command window and navigate to c:\glassfish
  3. type in: java -Xmx256m -jar glassfish-installer-9.0-b32.jar
  4. type in: C:\glassfish\glassfish\lib\ant\bin\ant -f setup.xml

On the first run of step 4, I learned from the feedback
that my port 8080 was already used, so I went into the setup.xml file
to change the instance.port property to 8085. In this setup.xml file –
in $GlassFish_HOME, which was in my case c:\glassfish\glassfish – you
can find other properties to specify port and username/password for the
GlassFish admin-console, imq, orb and https port numbers as well as the
default domain name. Unless you have port-conflicts, you do not need to
change anything in this file.

Start up Eclipse and create a new Java Project

Create a new Eclipse Java Project.

Configure the project


Set the JDK Compliance to (Java) 5.0:

Add the following libraries:

javaee.jar, toplink-essentials.jar (from the GlassFish_Home\lib directory) and dms.jar, ocrs12.jar and ojdbc14.jar (from an Oracle Client or JDBC installation).
The first three jars are taken from the GlassFish installation and represent the Reference Implementation for the EJB 3.0 javax.persistence interfaces. The other jars are only required when using the Oracle JDBC driver – they can be replaced with similar jars for any other JDBC driver.

Create Entities – POJOs with annotations that link them to database objects

I am really anxious to find out about out-of-container persistence with EJB 3.0. This is described for Glassfish on: GlassFish Project – Entity Persistence Support.
For some reason, the zip-file with example code that is mentioned on
this page fails to download. Well, the essential code samples are in
this page, so I will manage.

create one extremely simple POJO, that I decorate with EJB 3.0
annotations to instruct the EJB 3.0 EntityManager about mapping it to
a database table. Note: this is really the simplest set of annotations,
just to get the show going. I use the AMIS Library System, quite a popular case for workshops in my company.

package nl.amis.ejb30.als;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

public class Publisher implements Serializable {

    private Long id;

    private String locationInCountry;

    private byte[] logo;

    private String name;

    private String website;

    public Publisher() {

    public Publisher(Long id) { = id;

    @Column(name="ID",  nullable=false)
    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getLocationInCountry() {
        return locationInCountry;

    public void setLocationInCountry(String locationInCountry) {
        this.locationInCountry = locationInCountry;

    public byte[] getLogo() {
        return logo;

    public void setLogo(byte[] logo) {
        this.logo = logo;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getWebsite() {
        return website;

    public void setWebsite(String website) { = website;


Provide the persistence.xml file that links Entities (or Domain Classes or POJOs) to a database connection

crucial element that links the annotated classes to a specific database
in the case of out-of-container persistence is the persistence.xml.
This file is read upon instantation of the EntityManagerFactory. It
must be located in the classes/META-INF directory (or in one of the
jar-files on the classpath).

the persistence.xml file, a Persistence Unit is specified, a bundle of
Entities that are mapped to the same Database Connection. For my
example, persistence.xml maps to tables in my local Oracle database,
more specifically the ALS schema in that database:

<persistence xmlns="">
    <persistence-unit name="AlsPU">
        <!-- Provider class name is required in Java SE -->
        <!-- All persistence classes must be listed -->
            <!-- Provider-specific connection properties -->
            <property name="jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
            <property name="jdbc.connection.string" value="jdbc:oracle:thin:@localhost:1521:ORCL"/>
            <property name="jdbc.user" value="als"/>
            <property name="jdbc.password" value="als"/>
            <!-- Provider-specific settings -->
            <property name="toplink.logging.level" value="FINE"/>

provider element set up in this file makes use of
oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider. That
is the default GlassFish reference implementation EntityManagerFactory
implementation. Not an Oracle specific class. Allthough of course it is
very similar to the EMF that Oracle ships as part of its Toplink
commercial offering.

Create a Business Service class that provides Entity Services (like an out-of-container Session Bean)

order to isolate our application from persistency details, we implement
a Business Service that the application can talk to. This LibraryService
class provides a number of Publisher related services,
that are internally implemented using an EJB 3.0 EntityManager. The LibraryService class is very much like the SessionBean you would create for
in-container deployment. It looks like this:

package nl.amis.ejb30.als;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContextType;

public class LibraryService {
    public LibraryService() {
        EntityManagerFactory emf = 
        // create EntityManager
        EntityManager em = emf.createEntityManager();
        // note: alternative is EXTENDED EntityManager ; an EXTENDED EntityManager keeps objects attached
        // EntityManager em = emf.createEntityManager(PersistenceContextType.EXTENDED);

    private EntityManager _entityManager;

    public EntityManager getEntityManager() {
        return _entityManager;

    public void setEntityManager(EntityManager entityManager) {
        _entityManager = entityManager;

    public List<Publisher> findAllPublishers() {
        return getEntityManager().createQuery("select object(o) from Publisher o").getResultList();

    public Publisher findPublisher(Long id) {
        return getEntityManager().find(Publisher.class, id);

    public void savePublisher(Publisher publisher) {
        EntityTransaction tx = getEntityManager().getTransaction();
        // Commit the transaction

    public Publisher createPublisher(Long id, String name) {
        Publisher p = new Publisher();
        return p;
    public void removePublisher(Publisher p) {
      // note: we cannot simply pass in any object to be removed:
      // the object may not be "detached"; any object that was created or
      // retrieved by the EntityManager in the current transaction is not
      // detached; any object from outside the current transaction however is
      // considered detached. We "attach"  a detached object by "merging" it:
      // note2: if we were using an EXTENDED EntityManager, any object that
      // was retrieved at any time by the EntityManager - across Transaction
      // boundaries - would still be "attached"
      // create an attached Publisher object for the (possibly) detached p
      Publisher p2 = getEntityManager().merge(p);
      // remove the attached counterpart of the (potentially) detached p
    private EntityTransaction transaction;
    public void startTransaction() {
      transaction = getEntityManager().getTransaction();
    public void endTransaction() {

Create a Client that leverages the Business Service to do stuff

test or explore the functionality of our LibraryService, we create a simple
Service Consumer, a stand-alone J2SE application – in fact nothing more
than a single MAIN method- that calls upon the LibraryService to perform
various services. The Client browses through all Publishers creates and
persists a new one and then removes it again

package nl.amis.ejb30.als;

import java.util.Collection;

public class LibraryClient {
    public LibraryClient() {

    public static void main(String[] args) {
        LibraryService library = new LibraryService();
        System.out.println("List all Publishers:");
        Collection<Publisher> publishers = library.findAllPublishers();
        for (Publisher publisher : publishers) { 
        Publisher publisher = new Publisher();
        publisher.setId(new Long(44));
        publisher.setName("My Publishing House");
        // alternative: create (and persist) new publisher
        Publisher p = library.createPublisher(new Long(45), "Great Books Inc.");
               // now remove the new Publishers
        library.removePublisher(library.findPublisher(new Long(45)));

Run Application

The application looks now as follows on the file system


In order to run the EJB 3.0 Persistence application correctly, we have to create some run-options.
When we have created an application – a class with a main – like LibraryClient, we can set these options. From the context menu on the project, select Run As and Run. Now we can set the options for when running the project.

Go to the Arguments tab in the Run wizard and set the correct VM arguments: -javaagent:GLASSFISH_HOME/lib/toplink-essentials-agent.jar.

The Library application could look something like this:

Note: the table ALS_PUBLISHERS that is used in this example looks as follows:


You can insert some demo data from this script:

2, '', 'Wrox (label of Wiley Publishing)', 'us', 'Indianapolis (IN)'); 
3, '', 'Wiley and Sons', 'us', 'New York (NY)'); 
1, '', 'O''Reilly', 'us', 'Sebastopol, CA'); 
4, '', 'Manning Publications Co.', 'us', NULL); 
5, '', 'SUN Microsystems', 'us', NULL); 
6, '', 'McGrawHill', 'us', NULL); 

About Post Author

Lucas Jellema

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director and Oracle Developer Champion. Solution architect and developer on diverse areas including SQL, JavaScript, Kubernetes & Docker, Machine Learning, Java, SOA and microservices, events in various shapes and forms and many other things. Author of the Oracle Press book Oracle SOA Suite 12c Handbook. Frequent presenter on user groups and community events and conferences such as JavaOne, Oracle Code, CodeOne, NLJUG JFall and Oracle OpenWorld.
0 %
0 %
0 %
0 %
0 %
0 %

Average Rating

5 Star
4 Star
3 Star
2 Star
1 Star

10 thoughts on “Starting with EJB 3.0 Persistence in Eclipse 3.1 using the GlassFish Reference Implementation

  1. Hello;

    Upon running the LibraryClient I get:

    [TopLink Config]: 2007.11.21 01:13:06.554–ServerSession(32233307)–Thread(Thread[main,5,main])–The alias name for the entity class [class nl.amis.ejb30.als.Publisher] is being defaulted to: Publisher.
    [TopLink Info]: 2007.11.21 01:13:06.621–ServerSession(32233307)–Thread(Thread[main,5,main])–TopLink, version: Oracle TopLink Essentials – 2.0 (Build b58g-fcs (09/07/2007))
    Exception in thread “main” java.lang.NullPointerException
    at sun.jdbc.odbc.JdbcOdbcDriver.initialize(
    at sun.jdbc.odbc.JdbcOdbcDriver.connect(
    at java.sql.DriverManager.getConnection(
    at java.sql.DriverManager.getConnection(
    at oracle.toplink.essentials.sessions.DefaultConnector.connect(
    at oracle.toplink.essentials.sessions.DatasourceLogin.connectToDatasource(
    at oracle.toplink.essentials.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(
    at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.login(
    at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.deploy(
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.getServerSession(
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(
    at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerFactoryImpl.createEntityManagerImpl(
    at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerFactoryImpl.createEntityManager(
    at nl.amis.ejb30.als.LibraryService.(
    at nl.amis.ejb30.als.LibraryClient.main(

  2. I am attempting a JPA application in Java SE using Eclipse 3.2.1 and Maven2. My project structure in eclipse is:


    When I run my as a java application I get:

    Exception in thread “main” javax.persistence.PersistenceException: No Persistence provider for EntityManager named WorkOrder
    at javax.persistence.Persistence.createEntityManagerFactory(
    at javax.persistence.Persistence.createEntityManagerFactory(
    at mypackage.MyClass.init(
    at mypackage.MyClass.main(

    I’ve tried placing the persistence.xml is various different folders but with no luck. I was wondering if anyone would know how to fix this.

  3. I have one note and one question:
    A note. The properties names for GlassFish persistence implementation has been changed (see for details), and version element must be specified in presistence.xml as it’s required by the schema.

    A question: When did you last time tried to download the zip files with examples on GlassFish persistence example page? This links were broken for a short while in December, but has been fixed ever since.


  4. It seems that it can find the persistence.xml file, but the file does not have an entry for the AlsPU provider.
    In the code, we have this line:


    This refers to an entry in the persistence.xml file:

    The name attribute of the persistence-unit element must match exactly with the string passed to the createEntityManagerFactory method.

    It would seem that your persistence.xml file is there, but it does not contain the proper persistence-unit element.

    good luck!


  5. i cant make it work, when i try to execute it a have this error:

    Exception in thread “main” javax.persistence.PersistenceException: No Persistence provider for EntityManager named AlsPU
    at javax.persistence.Persistence.createEntityManagerFactory(
    at javax.persistence.Persistence.createEntityManagerFactory(
    at nl.amis.ejb30.als.LibraryService.(
    at nl.amis.ejb30.als.LibraryClient.main(

    Its like the project cant recognize the persistece.xml file, but i know it is in the classpath

  6. Yes, you may want to download Glassfish’s Eclipse WTP plugin.

    If you build your initial WebApp under a different app server, (like Tomcat), you’ll have to change the project runtime. To do that, follow the steps below:

    1. Right-click on the project, then select properties.
    2. Select “Project Facets”, and click “Add/Remove Project Facets” in the bottom right corner
    3. Check the Sun DD Files facet, select “Show Runtimes”, and select a GlassFish runtime from the list.

    Now, instead of seeing the Tomcat runtime library in the Package Explorer, you’ll see
    Glassfish’s library, which will contain the core Java EE5 libraries, including all the

  7. I’m running Eclipse 3.1.2 on JDK 1.5.06. My project is set to JDK 5.0 compliance.

    But none of the EJB 3.0 annotations are being recognized and I get compile time errors
    saying cannot resolve type.

    Is there a plugin that I must install?

Comments are closed.

Next Post

Spring is bursting out all over

In an article on dev2dev, BEA’s Bill Wroth observes the increase of the usage of the Spring framework on WebLogic customer sites. He writes: "As I travel around to customer sites, it seemingly comes up everywhere. I have seen it in large government agencies, financial companies, and internet companies. I […]
%d bloggers like this: