0

I'm a newbie at using frameworks in JAVA EE so when I'm trying to call a method of the entity manager it throws a java.lang.NullPointerException so I want to what I wrote this is an example of my dao implementation

@Repository
@Transactional
public class IUserDAOImpl implements IUserDAO{

    @PersistenceContext
    private EntityManager em;

    public void addUser(User u) {
        em.persist(u);
    }   
}

this is my service

@Service
public class IUserServiceImpl implements IUserService {

@Autowired
private IUserDAO dao = new IUserDAOImpl();

public void setDao(IUserDAO dao) {
    this.dao = dao;
}

public void addUser(User u) {
    dao.addUser(u);     
}

this is my action class

public class ConnectionAction extends ActionSupport {

User c = new User("a","b","c",11,"d",true);

@Autowired
public IUserService service;


public String execute() throws Exception {
    service.addUser(c);
        return SUCCESS;
}

the web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <display-name>Struts Blank</display-name>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<context-param>
<param-name>contextConfiguration</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>

the applicationContext.xml (although it's really messed up so if you noticed sometihng wrong plz tell)

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns:tx="http://www.springframework.org/schema/tx"     xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"     xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/util     http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/tx     http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<bean id="dao"
class="com.iticsys.GBO.dao.IUserDAOImpl">
</bean>

<bean id="service"
class="com.iticsys.GBO.services.IUserServiceImpl">
<property name="dao" ref="dao"></property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/GBO1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>

<bean id="persistenceUnitManager"
    class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<value>classpath*:META-INF/persistence.xml</value>
</property>
<property name="defaultDataSource" ref="dataSource"> </property>
</bean>

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"></property>
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="persistenceUnit" /> 
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean> 
<tx:annotation-driven transaction-manager="transactionManager" /> 
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.iticsys.GBO.dao" />
</beans>

persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
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_2_0.xsd"
version="2.0">
<persistence-unit name="persistenceUnit"
    transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>


    <properties>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/GBO1" />
        <property name="javax.persistence.jdbc.user" value="root" />
        <property name="javax.persistence.jdbc.password" value="" />

        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.hbm2ddl.auto" value="update" />
    </properties>
</persistence-unit>

and thank you so much in advance

flavio.donze
  • 7,432
  • 9
  • 58
  • 91
Mohamed Elalami
  • 149
  • 2
  • 12

2 Answers2

0

In implementation of class IUserDAOImpl you should instantiate the Object of EntityManager like

private EntityManager em = new EntityManager(/*constructor parameter if any*/);

or You can assign a reference of Object of EntityManager that you can create in your other subclasses like IUserServiceImpl, ConnectionAction.

For that you can add a method in your class IUserDAOImpl which receive that reference.like,

public void setEntityManager(EntityManager em_ref ){ em = em_ref;}
Parth Vishvajit
  • 295
  • 4
  • 13
  • that may work but I want it to be injected automatically by spring . – Mohamed Elalami Apr 08 '16 at 14:26
  • **Check out this:** [http://docs.spring.io/spring/docs/2.5.x/reference/orm.html#orm-jpa-straight] They are setting that `private reference` by `set...()` method. It means you have to pass the reference of EntityManager tomake the class working. If you don't , it will throw `NullPointerException`. – Parth Vishvajit Apr 08 '16 at 14:47
0
public class HibernateUtil {

static Logger logger = Logger.getLogger(HibernateUtil.class);

private static final String FAILED_TO_CREATE_SESSION_FACTORY_OBJECT = "Failed to create sessionFactory object.";
private static final SessionFactory sessionFactory = buildSessionFactory();
private static ServiceRegistry serviceRegistry;

private static SessionFactory buildSessionFactory() {

try {
    Configuration configuration = new Configuration();
    configuration.configure("./hibernate.cfg.xml");

    configuration.addAnnotatedClass(Calzz.class);

    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

    return configuration.buildSessionFactory(serviceRegistry);

} catch (Throwable ex) {

    logger.debug(FAILED_TO_CREATE_SESSION_FACTORY_OBJECT + ex);
    throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

}

Tiago Medici
  • 1,944
  • 22
  • 22