persistence@glassfish.java.net

Re: Out-of-container example?

From: Michael Bouschen <Michael.Bouschen_at_Sun.COM>
Date: Thu, 03 Nov 2005 13:40:40 +0100

Hi Marina,

attached you find a Main.java and a persistence.xml.

Class Main implements a main method that creates EMF, EM, starts a tx,
persists a new Customer, commits the tx and then runs an EJBQL query.
The persistence.xml lists the persistent classes from the application
domain, e.g. oracle.toplink.examples.Customer, etc. I added the values
for jdbc driver name, url, anme and password as <driver>, <url>, etc.
This needs to be changed according to the local environment.

You need to add the -javaagent option to the jvm call:
   java -javaagent:${glassfish.home}/lib/toplink-essentials-agent.jar Main

In addition to the jdbc driver I have the following jars from the
{glassfish.home}/lib directory in the classpath: asm.jar,
toplink-essentials.jar, antlr.jar, javaee.jar.

I hope this helps.

Regards Michael

> Michael, Tom,
>
> Can you give an example of persistence.xml
> and a main() method that constructs emf for
> a Java SE persistence?
>
> It'll be helpful to put this on the Entity
> Persistence web page.
>
> thanks,
> -marina
>





import java.util.List;

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

import oracle.toplink.examples.Customer;

/** */
public class Main {
    
    /** Sample code running creating an emf an*/
    public static void main (String[] args) {

        // Create EMF for a persistence unit called j2seEnvironment.
        EntityManagerFactory emf =
            Persistence.createEntityManagerFactory("j2seEnvironment");

        // create EM
        EntityManager em = emf.createEntityManager();

        // Get a transaction instance and start the transaction
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        // Create a new customer and persist it.
        Customer c = new Customer();
        c.setName("Michael Bouschen");
        em.persist(c);

        // Commit the transaction
        tx.commit();

        // run an EJBQL query selecting a customer by name
        String ejbql = "SELECT c FROM Customer c WHERE c.name = :name";
        Query query = em.createQuery(ejbql);
        query.setParameter("name", "Michael Bouschen");
        List result = query.getResultList();
        System.out.println("EJBQL query " + ejbql + " returns " + result);

    }
    
}