Refael Ben eli
Refael Ben eli

Reputation: 53

Ejb wont initialize entity manager

my english is not my native language so i am sorry in advanced for my poor english. My project is working well when i manage the transaction with entity manager, entity factory and get transactions. I want to use the ejb to handle the transactions for me. I did every thing needed in order for it to work but the ejb wont initalized the entity manager and he will stay null. i cant understand what i am doing wrong. i have configured my persistance.xml with jta data source and did all the annotations needed but still cant get it to work. what i try to create a query i get a null pointer exception and the entity manager is null. I have been searching and looking for a solution but did not succeed. I hope some one here can find the answer. Thank you for you time!

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="swap" transaction-type="JTA">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<jta-data-source>java:jboss/datasources/swap</jta-data-source>

		<class>org.Roper.WebService.Model.User</class>
		<class>org.Roper.WebService.Model.BaseEntity</class>
		<class>org.Roper.WebService.Model.Person</class>
		<class>org.Roper.WebService.Model.Admin</class>
		<class>org.Roper.WebService.Model.BusinessOwner</class>
		<class>org.Roper.WebService.Model.Business</class>
		<class>org.Roper.WebService.Model.Product</class>
		<class>org.Roper.WebService.Model.Category</class>
		<class>org.Roper.WebService.Model.Tourist</class>

		<exclude-unlisted-classes>false</exclude-unlisted-classes>
		<properties>
			<!-- Hibernate properties -->
			<property name="javax.persistence.jdbc.driver"
				value="org.postgresql.Driver" /> <!-- DB Driver -->
			<property name="hibernate.hbm2ddl.auto" value="update" />
			<property name="hibernate.connection.zeroDateTimeBehavior"
				value="convertToNull" />
			<property name="hibernate.show_sql" value="false" />
			<property name="hibernate.format_sql" value="true" />
			<property name="hibernate.dialect"
				value="org.hibernate.dialect.PostgreSQLDialect" />
			<property name="hibernate.transaction.jta.platform"
				value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform" />
			<!-- Database properties -->
			<property name="javax.persistence.jdbc.url"
				value="jdbc:postgresql://hidden/swap?useUnicode=yes&amp;characterEncoding=UTF-8" /> <!-- BD Mane -->
			<property name="javax.persistence.jdbc.user" value="hidden" /> <!-- DB User -->
			<property name="javax.persistence.jdbc.password"
				value="hidden" /> <!-- DB Password -->
		</properties>
	</persistence-unit>
</persistence>

This is the main class that call the ejb:

@Path("PersonService")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {
    private static final Logger logger = Logger.getLogger(PersonResource.class);

    @EJB
    PersonService personService = new PersonService();

    @GET
    @Path("/users")
    public List<Person> getUsers(@BeanParam FilterBean fb)
    {
        logger.info("Getting all users.");
        return personService.GetAllUsers();
    }
}

this is the service class that call the entity managet:

    @Stateless
@LocalBean
public class PersonService {

    private static final Logger logger = Logger.getLogger(PersonService.class);

    @PersistenceContext(unitName="swap")
    public EntityManager em;

    /**
     *This function is querying the database selecting all the person entities.
     *@return List of all the users from the database.
     */
    public List<Person> GetAllUsers()
    {
        logger.debug("Starting to get all users.");

        try {
            try {
                List<Person> users = em.createQuery("SELECT u FROM Person u").getResultList();
                logger.info("Success, got all users.");
                return new ArrayList<Person>(users);
            }
            catch(PersistenceException e)
            {
                if(e.getCause().getCause().getMessage().contains("ERROR: relation \"users\" does not exist"))
                {
                    logger.info("No users in the database.");
                }
                else
                {
                    logger.error("Error while getting users from the database, error: ", e);
                }
            }
        }catch(Exception e)
        {
            logger.error("Cant get the users, error: ",e);
        }
        return null;
    }

The datasource from the standalone-full.xml:

  <subsystem xmlns="urn:jboss:domain:datasources:5.0">
        <datasources>
            <datasource jndi-name="java:jboss/datasources/swap" pool-name="swap" enabled="true" use-java-context="true">
                <connection-url>jdbc:postgresql://127.0.0.1:5432/swap?useUnicode=yes&amp;characterEncoding=UTF-8</connection-url>
                <driver>org.postgresql</driver>
                <security>
                    <user-name>postgres</user-name>
                    <password>postgres</password>
                </security>
            </datasource>
            <drivers>
                <driver name="org.postgresql" module="org.postgresql">
                    <driver-class>org.postgresql.Driver</driver-class>
                    <xa-datasource-class>org.postgresql.Driver</xa-datasource-class>
                </driver>
            </drivers>
        </datasources>
    </subsystem>

Upvotes: 0

Views: 441

Answers (1)

Illya Kysil
Illya Kysil

Reputation: 1746

Following lines look suspicious:

@EJB
PersonService personService = new PersonService();

It should be either injected (so no = new PersonService();is needed) or created via constructor but that instance is not managed by any container and, as a consequence, no injection happens there and EntityManager em stays null.

Please update your code as follows:

@EJB
PersonService personService;

Beside that, Integrating JAX-RS with EJB Technology and CDI section of JavaEE 6 tutorial suggests that JAX-RS resources should be either EJBs themselves (so annotated with @Stateless or @Stateful) OR CDI beans (so annotated with @ApplicationScoped or @RequestScoped). I would suggest to add a @Stateless annotation on the PersonResource class itself.

Upvotes: 1

Related Questions