Error after .getCurrentSession() with Hibernate Spring - java

When getting Session with .getCurrentSession() getting the following error.
Error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'miniVLEController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: miniVLE.service.StudentService miniVLE.controller.miniVLEController.studentService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: miniVLE.dao.MiniVLEDAOImplementation miniVLE.service.StudentService.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'miniVLEDAOImplementation' defined in file [C:\Users\1\Documents\NetBeansProjects\com3014_mini_VLE\build\web\WEB-INF\classes\miniVLE\dao\MiniVLEDAOImplementation.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [miniVLE.dao.MiniVLEDAOImplementation]: Constructor threw exception; nested exception is java.lang.NullPointerException
DAO Implementation:
import java.util.ArrayList;
import java.util.List;
import miniVLE.beans.Course;
import miniVLE.beans.Department;
import miniVLE.beans.Module;
import miniVLE.beans.Student;
import miniVLE.beans.TimeSlot;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class MiniVLEDAOImplementation implements MiniVLEDAO{
// Used for communicating with the database
#Autowired
private SessionFactory sessionFactory;
/**
* DAO constructor filled with dummy data
*/
public MiniVLEDAOImplementation() {
System.out.println("*** MiniVLEDAOImplementation instantiated");
Student s1 = new Student("123456","Bob","123");
Department d1 = new Department("COM","Computing");
Course c1 = new Course("COM3014","Web");
c1.setDepartment(d1);
s1.setCourse(c1);
s1.setDept(d1);
// Add new student to the database
addStudentToDB(s1);
}
/**
* Gets the current session and adds new student row into the database
* #param student
*/
#Override
public void addStudentToDB(Student student) {
sessionFactory.getCurrentSession(); // here i got rid of full implementation as it fails on getting the current session
} ...
Dispatcher-Servlet:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="miniVLE.controller" />
<context:component-scan base-package="miniVLE.service" />
<context:component-scan base-package="miniVLE.beans" />
<context:component-scan base-package="miniVLE.dao" />
<!-- Declare a view resolver-->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!-- Connects to the database based on the jdbc properties information-->
<bean id="dataSource" class ="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name ="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name ="url" value="jdbc:derby://localhost:1527/minivledb"/>
<property name ="username" value="root"/>
<property name ="password" value="123" />
</bean>
<!-- Declares hibernate object -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> ${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<!-- A list of all the annotated bean files, which are mapped with database tables-->
<property name="annotatedClasses">
<list>
<value> miniVLE.beans.Course </value>
<value> miniVLE.beans.Student </value>
<value> miniVLE.beans.Department </value>
<value> miniVLE.beans.Module </value>
<value> miniVLE.beans.TimeSlot </value>
</list>
</property>
</bean>
</beans>

To create your beans, Spring first uses your class' no-argument constructor to create an instance and then uses reflection to autowire #Autowired fields.
But your constructor
public MiniVLEDAOImplementation() {
...
// Add new student to the database
addStudentToDB(s1);
}
calls a method that uses the SessionFactory before it has been initialized. It is therefore null and you get a NullPointerException when trying to call a method on it.
You cannot add the student to the database from that point. If you want to test out your class, try unit testing.

Related

Configuting Spring with Hibernate.Error creating bean with name 'usersDao': Unsatisfied dependency expressed through field 'sessionFactory'

I am trying to configure Spring 4 with Hibernate 5.Made a google research but it didn't help. I am launching my app with JUnit test, just to see if Hibernate works.
Error creating bean with name 'usersDao': Unsatisfied dependency expressed through field 'sessionFactory': Error creating bean with name 'sessionFactory' defined in class path resource [ConfigTest/datasource.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.cfg.Configuration.<init>(Lorg/hibernate/boot/MetadataSources;)V; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [ConfigTest/datasource.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.cfg.Configuration.<init>(Lorg/hibernate/boot/MetadataSources;)V
This is my datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:component-scan base-package="/WebMVCtest/test/Config">
</context:component-scan>
<beans profile="dev">
<context:property-placeholder
location="ConfigTest/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>DAO</value>
</list>
</property>
</bean>
</beans>
</beans>
Also When I use Hibernate 4 I face an error :
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'offersDao': Injection of autowired dependencies failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/cache/spi/RegionFactory
but I do have RegionFactory at that address:
enter image description here
Thanful in advance!
It appears that the packagesToScan property wants an array.
In your case, I suppose it would look like this...
<property name="packagesToScan">
<array>
<value>DAO</value>
</array>
</property>
Or maybe simply...
<property name="packagesToScan" value="DAO" />
The problem was in compatability of versions. So I used Spring 4.0.3.RELEASE and Hibernate 4.3.5.Final and the error is gone.
Also I had an error : no current session found. So I've refractored a little a transaction bean :
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven />

Spring unit testing and InitialContext

I would like to get a simple integration test with Tomcat and Spring 4 running, injecting a spring component and use my existing data source configuration from Tomcat. I don't want to configure my DataSource twice.
Everything, including my data source, is configured in the file WebContent/WEB-INF/application-context.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
<!-- annotations in bean classes -->
<!-- context:annotation-config / -->
<!-- mvc:annotation-driven / -->
<context:component-scan base-package="com.mycompany.package.**" />
<jpa:repositories base-package="com.mycompany.package.**" />
<!-- <aop:aspectj-autoproxy proxy-target-class="true"/> -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="packagePU" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
</property>
<property name="jpaPropertyMap">
<props>
<prop key="eclipselink.weaving">false</prop>
</props>
</property>
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="generateDdl" value="false" />
<property name="showSql" value="true" />
</bean>
<bean id="jpaDialect"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
<!-- <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"/> </bean> -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="i18n/messages" />
</bean>
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/DefaultDB" />
</beans>
I am using this tutorial http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-ctx-management, but I don't fully understand how I can just run my test in the context of Tomcat that provides my DataSource.
Currently, I am this far:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = { "file:WebContent/WEB-INF/application-context.xml"})
public class SimulatorTest {
#Autowired
private ShiftSimulator simulator;
#BeforeClass
public void setup() {
// ???
}
#Test
public void testShiftStart() {
System.out.println("Hello world");
}
}
Currently, I get this error when running the test
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:WebContent/WEB-INF/application-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
...
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
...
I fully understand that there needs to be a InitialContext, but how can I provide my test with my context that is provided by Tomcat, including my Data Source configuration? I don't want to set my data source connection credentials twice.
Solved it. Just to recap the problem: Spring tries to create the dataSource bean and fails at looking up the JNDI name - because there is no JNDI available.
So what I did for testing, I just created another XML files that overrides the bean dataSource. I ignored the file in version control and ask every developer to copy this file in place:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.sap.db.jdbc.Driver"
p:url="jdbc:sap://xxx:30015"
p:username="sa"
p:password="">
</bean>
</beans>
In the test class, I am providing the additional file reference that overrides dataSource so it never tries to do the failing JNDI lookup:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = { "file:WebContent/WEB-INF/application-context.xml", "file:WebContent/WEB-INF/test-datasource.xml" })
public class SimulatorTest {
...
TomcatJNDI offers a comfortable solution for this problem. It's based on Tomcat's JNDI system and initializes only Tomcat's JNDI environment without starting the server. So you can access all your resources as configured in Tomcat's configuration files in tests or from within any Java SE application. Usage is simple, e. g.
TomcatJNDI tomcatJNDI = new TomcatJNDI();
tomcatJNDI.processContextXml(contextXmlFile);
tomcatJNDI.start();
DataSource ds = (DataSource) InitialContext.doLookup("java:comp/env/path/to/datasource");
Find more about it here.

Spring initialisation error: java.lang.IncompatibleClassChangeError: Implementing class

I'm getting this exception and I can't figure out why. CheckoutItem and the interface CheckoutItemDAO are in a separate jar and are simple javabeans without any annotations. CheckoutItemDAOHibernate implements CheckoutItemDAO
16:26:31,135 ERROR [ContextLoader:227] Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'checkoutService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.newscom.dao.CheckoutItemDAO com.liferay.webform.business.CheckoutService.checkoutItemDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'checkoutItemDAO' defined in ServletContext resource [/WEB-INF/context/applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/context/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Implementing class
CheckoutService.java
package com.liferay.webform.business;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.newscom.dao.CheckoutItemDAO;
import com.newscom.model.CheckoutItem;
#Service
#Transactional
#Controller
public class CheckoutService {
#Autowired private CheckoutItemDAO checkoutItemDAO;
public CheckoutItem getCheckoutItemById(Integer checkoutItemId) {
List<CheckoutItem> items = checkoutItemDAO.retrieveRecordByID(checkoutItemId);
if (items != null && items.size() > 0) {
return items.get(0);
}
else {
return null;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans 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:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:component-scan base-package="com.liferay.webform.business" />
<tx:annotation-driven/>
<util:properties id="applicationProperties" location="classpath:application.properties"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/ncdb"></property>
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.newscom.model.CheckoutItem</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">false</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">false</prop>
<prop key="hibernate.connection.release_mode">auto</prop>
<prop key="hibernate.query.substitutions">true 1, false 0</prop>
</props>
</property>
</bean>
<bean id="daoTemplate" abstract="true">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean parent="daoTemplate" id="checkoutItemDAO" class="com.newscom.dao.hibernate.CheckoutItemDAOHibernate" />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

Log says that the autowire was done, but a NPE is thrown when the object is used

I'm trying to inject a DAO using #Autowire. Setting the log level to debug, I can see that the bean was created and wired to the service class, but, when I try to use the injected object, a nullpointerexecption is thrown.
English is not my primary language, but looking into the log bellow, it seems that the DAO was created and properly wired to the service:
DefaultListableBeanFactory:221 - Creating shared instance of singleton bean 'ticketServiceImpl'
DefaultListableBeanFactory:450 - Creating instance of bean 'ticketServiceImpl'
InjectionMetadata:72 - Registered injected element on class [br.com.xpto.sys.business.impl.TicketServiceImpl]: AutowiredFieldElement for private br.com.xpto.sys.dao.api.TicketDAO br.com.xpto.sys.business.impl.TicketServiceImpl.dao
DefaultListableBeanFactory:523 - Eagerly caching bean 'ticketServiceImpl' to allow for resolving potential circular references
InjectionMetadata:86 - Processing injected element of bean 'ticketServiceImpl': AutowiredFieldElement for private br.com.xpto.sys.dao.api.TicketDAO br.com.xpto.sys.business.impl.TicketServiceImpl.dao
DefaultListableBeanFactory:221 - Creating shared instance of singleton bean 'ticketDAOImpl'
DefaultListableBeanFactory:450 - Creating instance of bean 'ticketDAOImpl'
AnnotationTransactionAttributeSource:108 - Adding transactional method 'TicketDAOImpl.findByTicketNumber' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
InfrastructureAdvisorAutoProxyCreator:538 - Creating implicit proxy for bean 'ticketDAOImpl' with 0 common interceptors and 1 specific interceptors
JdkDynamicAopProxy:115 - Creating JDK dynamic proxy: target source is SingletonTargetSource for target object [br.com.xpto.sys.dao.impl.TicketDAOImpl#2242b3b8]
DefaultListableBeanFactory:478 - Finished creating instance of bean 'ticketDAOImpl'
AutowiredAnnotationBeanPostProcessor:480 - Autowiring by type from bean name 'ticketServiceImpl' to bean named 'ticketDAOImpl'
DefaultListableBeanFactory:478 - Finished creating instance of bean 'ticketServiceImpl'
The NPE ocurrs into the dao.findByTicketId(ticketId) call. Since dao is null, it throws the exception.
I tried to do minor changes after that I read this and this posts, but with no lucky.
Below I posted the main parts of the code. Any advice is welcome.
UPDATE
As requested, I'm also posting how do I instantiate the TicketServiceImpl class and the stack trace.
The class is instantiated inside an ItemProcessor bean (spring batch)
public class TicketItemProcessor implements ItemProcessor<Ticket, TicketLog> {
#Override
public TicketLog process(Ticket item) throws Exception {
TicketServiceImpl srv = new TicketServiceImpl();
Ticket t = srv.findByTicketId(item.getIdTicket());
return new TicketLog();
}
}
TicketServiceImpl
#Service
public class TicketServiceImpl implements TicketService {
#Autowired
private TicketDAO dao;
#Override
public Ticket findByTicketId(int ticketId) {
return dao.findByTicketId(ticketId);
}
}
TicketDAOImpl
#Repository
public class TicketDAOImpl extends implements TicketDAO {
#Override
public Ticket findByTicketId(int ticketId) {
String jpql = "SELECT t FROM Ticket t WHERE t.id = :ticketId";
Query query = getSession().createQuery(jpql);
query.setParameter("ticketId", ticketId);
query.setMaxResults(1);
Object obj = query.uniqueResult();
return (Ticket) obj;
}
}
TicketDAO
public interface TicketDAO extends DAO<Ticket> {
Ticket findByTicketId(int ticketId);
}
DAO
public interface DAO<E> extends Serializable {
List<E> listAll();
}
context.xml
<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:batch="http://www.springframework.org/schema/batch" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd">
<context:annotation-config />
<context:component-scan base-package="br.com.xpto.sys" />
<bean id="dbDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://server;databaseName=db" />
<property name="username" value="usr" />
<property name="password" value="pwd" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dbDataSource" />
<property name="packagesToScan" value="br.com.xpto.sys.model.entities" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">br.com.xpto.sys.dao.utils.SQLServerDialectOverrider</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">false</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
Stack Trace
AbstractStep:222 - Encountered an error executing step step1 in job job-ProcessTickets
java.lang.NullPointerException
at br.com.xpto.sys.business.impl.TicketServiceImpl.findByTicketId(TicketServiceImpl.java:83)
at br.com.xpto.sys.jobs.spring.TicketItemProcessor.process(TicketItemProcessor.java:24)
at br.com.xpto.sys.jobs.spring.TicketItemProcessor.process(TicketItemProcessor.java:1)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.doProcess(SimpleChunkProcessor.java:126)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.transform(SimpleChunkProcessor.java:293)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.process(SimpleChunkProcessor.java:192)
at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:75)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:395)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:267)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:77)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:368)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144)
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:253)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:195)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:141)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:64)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:151)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:130)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:301)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:134)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:127)
at br.com.xpto.sys.jobs.AppStandalone.run(AppStandalone.java:111)
at br.com.xpto.sys.jobs.AppStandalone.main(AppStandalone.java:75)

Could not autowire field while inserting data into the database

Question title may be same, but I tried to solve this error by looking at previous answers, but nothing happen. I'm getting following error while insert data into the database. Tables are created, but there is an error while inserting data into the database.
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'InitDbService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.app.flight.repo.RoleRepository com.app.flight.service.InitDbService.roleRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'roleRepository': Cannot create inner bean '(inner bean)#397030fe' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#397030fe': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
This is my Role.java entity class
#Entity
public class Role {
#Id
#GeneratedValue
private Integer id;
private String name;
(getters and setters)
This is RoleRepository.java interface
package com.app.flight.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.app.flight.entity.Role;
public interface RoleRepository extends JpaRepository<Role, Integer> {
}
This is service class InitDbService.java
package com.app.flight.service;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.app.flight.entity.Role;
import com.app.flight.repo.RoleRepository;
#Transactional
#Service
public class InitDbService {
#Autowired
private RoleRepository roleRepository;
#PostConstruct
public void init(){
Role roleUser = new Role();
roleUser.setName("ROLE_USER");
roleRepository.save(roleUser);
Role roleAdmin= new Role();
roleAdmin.setName("ROLE_ADMIN");
roleRepository.save(roleAdmin);
}
}
This is applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans 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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.7.xsd">
<context:component-scan base-package="com.app.flight">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<jdbc:embedded-database type="HSQL" id="dataSource"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="emf">
<property name="packagesToScan" value="com.app.flight.entity"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<jpa:repositories base-package="com.app.flight.repo"/>
</beans>
It expects that the EntityManagerFactory has a specific name in that case "entityManagerFactory". You defined a custom name "emf". I assume the problem is resolved if you adapt the entry in the xml file.

Categories