Java 5 annotation does not work

M

Marioli

Hi all,

I have modified slightly (to learn from it:) NetBeans 5.5 JsfJpa
example application and thus coused it to stop working. I get
NullPointerException. I have made following modifications:

I have modified getUser() call in UserManager class to delegate the job
to the different class:

private Wuser getUser() {
/* try {
Wuser user = (Wuser)
em.createNamedQuery("Wuser.findByUsername").
setParameter("username",
username).getSingleResult();
return user;
} catch (NoResultException nre) {
return null;
}
*/
return (new
dao.UserPersistenceServiceBean()).getUserByName(username);
}

and added new class:

package dao;

import enterprise.jsf_jpa_war.Wuser;

import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

public class UserPersistenceServiceBean {
@PersistenceContext
private EntityManager em;

public Wuser getUserByName( String userName ) {
try {
return
(Wuser)em.createNamedQuery("Wuser.findByUsername").setParameter("username",
userName).getSingleResult();
} catch( NoResultException nrExc ) {
return null;
}
}
}

the result is:

java.lang.NullPointerException
dao.UserPersistenceServiceBean.getUserByName(UserPersistenceServiceBean.java:15)

The problem is that em variable (EntityManager) is null... but why? And
how to fix it? Please help:)

Regards
Mariusz Lipiñski
 
B

bg

Of course em is null, you haven't instantiated it!

You need something like:
private EntityManager em = new EntityManager(...);
 
D

Daniel Dyer

Of course em is null, you haven't instantiated it!

You need something like:
private EntityManager em = new EntityManager(...);

Well that is the problem, but the expectation for it to be non-null is not
unreasonable. The OP is using the PersistenceContext annotation to
express a dependency on the EntityManager. The idea is that the
application server should inject the dependency so that it is not
necessary to instantiate the EntityManager. Presumably the OP is not
running this example inside an application server, or the application
server is mis-configured.

Dan.
 
M

Marioli

Yes, application server is suposed to set this dependency...
application is running on Sun AS 9 and JDK 1.5. Before I've made this
simple modification it was all ok - dependencies were set by AS so I
guess AS is configured just OK. Well... Java 5 looks great at first
sight and then... strange difficulties. Why I don't have an exception
that the dependency cannot be set becouse of...

Regards
Mariusz Lipiñski
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top