Esben Skov Pedersen
Esben Skov Pedersen

Reputation: 4517

How to use JPA outside of a web project?

I've used eclipselink in a web project in NetBeans. It works nice and easy. How can I do the same in a project unrelated to the web (console application)?

In my web application I have:

@PersistenceUnit
EntityManagerFactory enf;

Which instantiates enf. This does not work in a console application.

Upvotes: 2

Views: 1489

Answers (3)

Manoj
Manoj

Reputation: 1394

In case of an Web or an application container, the container injects the EntityManagerFactory when the @PersistenceUnit annotation is called. This will not hold good for a console application.

The possible ways for achieving this are

  1. To include Spring (which does the same job as your web container). Please refer to the tutorial Getting Started With JPA in Spring 2.0

Or

  1. To write the initiation code yourself as follows.

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceUnitName");
    

Upvotes: 3

Doug Clarke
Doug Clarke

Reputation: 550

When running within an EJB3 container (or Spring) you get the benefits of dynamic weaving with EclipseLink. If you are running in a JavaSE scenario I would recommend using the -javaagent to enable dynamic weaving so your application behaves the same.

Docs: http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#How_to_Configure_Dynamic_Weaving_for_JPA_Entities_Using_the_EclipseLink_Agent

Doug

Upvotes: 1

Esben Skov Pedersen
Esben Skov Pedersen

Reputation: 4517

Ok, I just need to call

enf = Persistence.createEntityManagerFactory("JavaApplication39PU");

Where JavaApplication39PU is the name found in META-INF/persistence.xml

Upvotes: 2

Related Questions