Home EntityManager is null in EJB
Reply: 1

EntityManager is null in EJB

lianyouCat
1#
lianyouCat Published in 2018-01-11 10:59:39Z

My client runs on Tomcat and Server is on Wildfly 11.

The EJB is:

package dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import model.User;

@Stateless
public class UserDaoImpl implements UserDao {
@PersistenceContext(unitName = "nju")
protected EntityManager em;

@Override
public String login(String userName, String password) {
    try {
        Query query = em.createQuery("from User u where u.userName='" + userName + "'");
        @SuppressWarnings("unchecked")
        List<User> list = query.getResultList();
        em.clear();
        if (list.isEmpty()) {
            return "failure";
        } else if (list.get(0).getPassword().equals(password)) {
            return "success";
        }
    } catch (Exception e) {
        e.printStackTrace();
        return "failure";
    }
    return "failure";
}
}

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="nju">
    <description>This unit manages users.</description>
    <jta-data-source>java:/MySqlDS</jta-data-source>
    <properties>
        <property name="showSql" value="true" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
    </properties>
</persistence-unit>

When I run server, the output contains

18:53:38,997 INFO [org.jboss.as.clustering.infinispan] (ServerService Thread Pool -- 62) WFLYCLINF0002: Started client-mappings cache from ejb container 18:53:39,005 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 62) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service 'J2EEServer.war#nju'

So the location of persistence.xml is not wrong.

However, when I run client and call the function in EJB. There is NullPointerException which indicates that the entitymanager is not injected.

In client I use a factory to get EJB. The method is

private static Object getEJB(String JNDIPath) {
    Hashtable<String, String> jndiProperties = new Hashtable<>();
    jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
    try {
        Context context = new InitialContext(jndiProperties);
        return context.lookup(JNDIPath);
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return null;

}

The exception only shows on wildfly and when it occurs, the tomcat message is

 org.jboss.ejb.client.EJBClient <clinit>
INFO: JBoss EJB Client version 2.1.4.Final
org.xnio.Xnio <clinit>
INFO: XNIO version 3.4.0.Final
org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.4.0.Final
org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 4.0.21.Final
org.jboss.ejb.client.remoting.VersionReceiver handleMessage
INFO: EJBCLIENT000017: Received server version 3 and marshalling strategies [river]
org.jboss.ejb.client.remoting.RemotingConnectionEJBReceiver associate
INFO: EJBCLIENT000013: Successful version handshake completed for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext@51e6ae57, receiver=Remoting connection EJB receiver [connection=org.jboss.ejb.client.remoting.ConnectionPool$PooledConnection@5281b661,channel=jboss.ejb,nodename=microwin10-115]} on channel Channel ID 8d8bb52c (outbound) of Remoting connection 3607d423 to localhost/127.0.0.1:8080 of endpoint "client-endpoint" <41cb456e>
org.jboss.ejb.client.remoting.ChannelAssociation$ResponseReceiver handleEnd
INFO: EJBCLIENT000016: Channel Channel ID 8d8bb52c (outbound) of Remoting connection 3607d423 to localhost/127.0.0.1:8080 of endpoint "client-endpoint" <41cb456e> can no longer process messages

How can I solve this problem?

lianyouCat
2#
lianyouCat Reply to 2018-01-12 02:27:46Z

I finally find the solution!!

In my project, my previous Service code is

@Stateless
public class UserServiceImpl implements UserService {

private UserDao userdao=Factory.getUserDao();

@Override
public String login(String userName, String password) {
    return userdao.login(userName, password);
}

@Override
public String register(User user) {
    return userdao.register(user);
}

}

And in the Factory, I get the object by using new UserDaoImpl(). That's the question!

The EntityManager will not be injected if the object is used like this way.

So I delete the Factory and change the code in Service

@Stateless
public class UserServiceImpl implements UserService {
/**
 * Will be injected
 */
@EJB
private UserDao userdao;

@Override
public String login(String userName, String password) {
    return userdao.login(userName, password);
}

@Override
public String register(User user) {
    return userdao.register(user);
}

}

That works perfectly.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.313137 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO