users@glassfish.java.net

Re: Glassfish, JPA, can't get it to work.

From: Sahoo <sahoo_at_sun.com>
Date: Wed, 21 May 2008 15:19:13 +0530

The problem is that you are expecting injection to work for your
unmanaged class called DAO. In Java EE, only managed classes, such as
EJB, Filters, Servlets, etc., can use dependency injection. In your
DAO class, you can look up the EntityManager using JNDI as show below:

new InitialContext().lookup("java:comp/env").lookup("persistence/MyEM");

For this to work, you have to add a <persistence-context-ref> element in
your ejb-jar.xml or web.xml and give it a JNDI name persistence/MyEM.

HTH,
Sahoo

glassfish_at_javadesktop.org wrote:
> The EntityManger always null with:
>
> [code]
> @PersistenceContext(unitName = "punit")
> private EntityManager em;
> [/code]
>
> Here is the config.
> [code]
> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:ns2="http://java.sun.com/xml/ns/persistence/orm" 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">
> <persistence-unit name="punit" transaction-type="JTA">
> <provider>org.hibernate.ejb.HibernatePersistence</provider>
> <jta-data-source>jdbc/public_PostgreSQL</jta-data-source>
> <class>com.test.MyEntity</class>
> <exclude-unlisted-classes>true</exclude-unlisted-classes>
> <properties>
> <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/test"/>
> <property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
> <property name="hibernate.connection.password" value="test"/>
> <property name="hibernate.connection.username" value="test"/>
> <property name="hibernate.hbm2ddl.auto" value="update"/>
> </properties>
> </persistence-unit>
> </persistence>
> [/code]
>
> Hrere is the code:
>
> [code]
> public class DAO {
> @PersistenceContext(unitName = "punit")
> private EntityManager em;
>
> public EntityManager getEm() {return em;}
>
> public void setEm(EntityManager em) {this.em = em;}
>
> public void submit(MyEntity e) {
> em.persist(e); // em is always null
> }
> }
> [/code]
>
> I have a feeling I am doing something very wrong?
> Any tips appreciated.
>
> Thanks.
> [Message sent by forum member 'marlor' (marlor)]
>
> http://forums.java.net/jive/thread.jspa?messageID=275678
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_glassfish.dev.java.net
> For additional commands, e-mail: users-help_at_glassfish.dev.java.net
>
>