java.lang.NoClassDefFoundError: org/hibernate/util/DTDEntityResolver - java

I get error when i run , i used Spring MVC + Hibernate, spring 3.2 release and hibernate 4 release.
As below my code in model , servlet xml , and list of all libraries were added to path WEB-INF/lib .
1- FEP_Health_Model
package Models;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
public class FEP_Health_Model {
#Autowired
private SessionFactory factory;
public FEP_Health_Model()
{
System.out.print("Hello Spring MVC with Hibernate");
try{
configureSessionFactory();
}catch(Throwable ex){
System.err.println("Failed to create sessionFactory object." + ex); throw new
ExceptionInInitializerError(ex);
}
}
#Transactional
public void test()
{
Session session = factory.openSession();
Transaction trans = null;
try{
trans = session.beginTransaction();
/*
Some Code
*/
trans.commit();
}catch(Throwable ex){
}finally{
session.close();
}
}
private void configureSessionFactory() throws HibernateException {
AnnotationConfiguration configuration = new AnnotationConfiguration();
configuration.configure().addAnnotatedClass(FepEnergyData.class);
factory = configuration.buildSessionFactory();
}
}
2- springmvc-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-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="Controllers"></context:component-scan>
<context:component-scan base-package="Models"></context:component-scan>
<context:annotation-config />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/JSP/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url"
value="jdbc:sqlserver://127.0.0.1:1433;databaseName=AECMDMS_TEST;instanceName=SQLEXPRESS;"/>
<property name="username" value="user"/>
<property name ="password" value="123" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>/META-INF/hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.SQLServer2008Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:jta-transaction-manager transaction-manager="transactionManager"/>
</beans>
3- ٍlist of all libraries have been added
commons-digester3-3.2.jar
commons-io-2.4.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
ejb3-persistence.jar
hibernate-annotations-3.5.6-Final.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.5.Final.jar
hibernate-envers-4.2.5.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
log4j.jar
org.osgi.core-4.3.1.jar
org.springframework.aop-3.2.0.RELEASE.jar
org.springframework.beans-3.2.0.RELEASE.jar
org.springframework.context-3.2.0.RELEASE.jar
org.springframework.core-3.2.0.RELEASE.jar
org.springframework.jdbc-3.2.0.RELEASE.jar
org.springframework.orm-3.2.0.RELEASE.jar
org.springframework.transaction-3.2.0.RELEASE.jar
org.springframework.web.servlet-3.2.0.RELEASE.jar
org.springframework.web-3.2.0.RELEASE.jar
spring-webmvc-3.2.0.RELEASE.jar
spring-asm-3.2.0.M1.jar
spring-tx-3.2.0.RELEASE.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
slf4j-simple-1.7.5.jar
sqljdbc4.jar
xalan-2.7.1.jar
xercesImpl.jar
xml-apis.jar
Console
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'sessionFactory' defined in ServletContext resource [/WEB-INF/FEP_Health-servlet.xml]:
Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError:
org/hibernate/util/DTDEntityResolver
i hope anybody find solution for My problem

Per the Hibernate annotations 3.5 documentation:*
Hibernate 3.5 and onward contains Hibernate Annotations.
You should remove the dependency on hibernate-annotations, and remove the excludes from the hibernate-entitymanager dependency. Generally, you should not mix versions of dependent packages.
This is work for me.

Had the same error message.
Removing the dependency on hibernate-annotations from the pom (as described by Prem above) solved the issue and Hibernate went on to generate the schema (in my case).

Related

Java Spring MVC + Hibernate - sessionFactory "unsatisfied dependency" errror

I'm in the middle of creating my first Spring + Hibernate webapp and this is what I have in console:
Root Cause
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'quizDAOImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.kubacki.entity.Quiz
I tried to find already existing solutions but nothing seems to work, would you be able to help me please?
I am not sure if the issue may be caused by bad XML configuration or some mistake in coding itself, from my perspective "sessionFactory" bean is correctly configured in XML and there should be no problem with injecting it.
Additionally, I'am using Maven for this project but I have already listed all spring + hibernate stuff in pom.xml
Here is my source code:
QuizDAO:
package com.kubacki.dao;
import java.util.List;
import com.kubacki.entity.Quiz;
public interface QuizDAO {
public Quiz getQuiz(int id);
public List<Quiz> getQuizzes();
}
QuizDAOImpl:
package com.kubacki.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.kubacki.entity.Quiz;
#Repository
public class QuizDAOImpl implements QuizDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public Quiz getQuiz(int id) {
Session tempSession = sessionFactory.getCurrentSession();
Quiz tempQuiz = tempSession.get(Quiz.class, id);
return tempQuiz;
}
#Override
public List<Quiz> getQuizzes() {
Session tempSession = sessionFactory.getCurrentSession();
Query<Quiz> theQuery = tempSession.createQuery("from quiz", Quiz.class);
List<Quiz> tempQuizzes = theQuery.getResultList();
return tempQuizzes;
}
}
Web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>WebApp</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.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:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.kubacki" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/quizdb?useSSL=false" />
<property name="user" value="root" />
<property name="password" value="admin" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.kubacki.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
As per the error
No identifier specified for entity: com.kubacki.entity.Quiz
I think, You are missing a field annotated with #Id in Quiz class. Each #Entity must have an #Id - this will be a primary key in your database.

Spring 4 and Hibernate 4/c3p0 with Entity Manager don't start

I create the configuration of Spring + JPA/Hibernate/c3p0 on this way:
Spring-Servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.nassoft.erpweb"/>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<mvc:annotation-driven />
<mvc:interceptors>
<bean class="com.nassoft.erpweb.login.interceptor.AuthenticatorInterceptor" />
</mvc:interceptors>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.nassoft.erpweb.*" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/nsm_erp" />
<property name="user" value="root" />
<property name="password" value="1234" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxStatements" value="50" />
<property name="idleConnectionTestPeriod" value="3000" />
<property name="loginTimeout" value="300" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
I'm not using persistence.xml because I read in some places its not necessary in Spring 4 with Hibernate.
When I start the server it still loading and don't start in 45s (nor 180s) in Tomcat7.
I create a factory of EntityManager to use in my project:
package com.nassoft.erpweb.factory;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
public class ConnectionFactory {
#PersistenceUnit
private static EntityManagerFactory entityManagerFactory;
public static EntityManager getEntityManager(){
if (entityManagerFactory == null){
entityManagerFactory = Persistence.createEntityManagerFactory("ERPWeb");
}
return entityManagerFactory.createEntityManager();
}
}
I think my configuration is not correct, but I don't found any places with a good text about it.
Can someone help-me?
Edited.
Problem solved!
First: I applied Dependency Injection in each controller to bring the DAOs with IoC.
Second: I use the annotation #Repository to create a repository in each DAO that will receive my databases methods.
Third: I created the EntityManage in this way for each DAO:
#PersistenceContext
private EntityManager manager;
This is not a complete answer. I"m just pointing you to a direction.
Spring cannot find the ConnectionFactory class of yours, so it will not inject the entityManagerFactory. Its not required for you to again create a singleton for passing the entityManager, so no ConnectionFactory class is required. Spring will do it for you by injecting into the DAO or Controller etc., for example you have the following DAO that gets the data.
#Service
public class SomeDAO {
#AutoWire -- i'm not sure what you call for the entityManager.
private static EntityManagerFactory entityManagerFactory;
}
There is more info here. Instead of #autowiring he is using manual injection. I your case ,you can try with autowiring.
Also make sure that you have these classes in the <spring:component-scan /> path of the application context file or else the spring wont be able to recognize and inject the entity manager.

SessionFactory injection isn't working

My SessionFactory isn't being injected to SessionFactory variable. My configuration is as follows:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.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">
<mvc:annotation-driven/>
<tx:annotation-driven/>
<context:annotation-config/>
<!-- Scans the package for contents -->
<context:component-scan base-package="com.csu.library.mvc"/>
<!-- Maps static resources like images, css, javascript files -->
<mvc:resources location="/resources/" mapping="/resources/**"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "viewClass" value = "org.springframework.web.servlet.view.JstlView"/>
<property name = "prefix" value = "/WEB-INF/jsps/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/csu_library"/>
<property name="username" value="csulibrary"/>
<property name="password" value="csulibrary"/>
<!-- Pool Properties -->
<property name="initialSize" value="5" />
<property name="maxIdle" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id = "hibernateProperties" class = "java.util.Properties">
<constructor-arg index="0">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
</props>
</constructor-arg>
</bean>
<bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value = "com.csu.library.mvc"/>
<property name="dataSource" ref = "dataSource"/>
<property name="hibernateProperties" ref = "hibernateProperties"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name = "sessionFactory" ref = "sessionFactory"/>
</bean>
</beans>
HibernateUtil.class
package com.csu.library.mvc.hibernate;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#org.springframework.context.annotation.Configuration
#EnableTransactionManagement
public class HibernateUtil {
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Bean
public HibernateTransactionManager transactionManager() {
return new HibernateTransactionManager(getSessionFactory());
}
#Bean
public HibernateExceptionTranslator exceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
The program throws NullPointerException when getSessionFactory() method is called. Obviously, sessionFactory isn't being injected. The program starts up fine. What could be the problem?
inject like following, it'll work fine
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
public Session getSession() {
return sessionFactory.getCurrentSession();
}
Hope to help you:)
In some Spring versions, sub folders are not scanned.
Either move your class in the package com.csu.library.mvc or add the package com.csu.library.mvc.hibernate in the scanned packages and give it a try.
You'll want to use the org.springframework.beans.factory.annotation.Autowired annotation instead of javax.inject.Inject.
#Autowired
private SessionFactory sessionFactory;
Note that only looks for annotations on beans in the same
application context it is defined in. This means that, if you put in
a WebApplicationContext for a DispatcherServlet, it only checks for #Autowired beans in your
controllers, and not your services.

Can not use external jar file's autowired class in parent project

My project works fine with autowired options as standalone and i create a jar file from this project.Problem comes after i added this jar to parent project, when i try to use external jar file's class in my parent project i got error like "Exception in thread "main" java.lang.NullPointerException...".
But if i don't use autowired option in my external jar file and write code fill context manually.Then external jar file works fine with my parent project.
External Jar File With Autowired Class
public class UserService {
#Autowired
UserRepository userRepository;
#Autowired
Movie2Repository movieRepository;
#Autowired
PersonRepository personRepository;
ConfigurableApplicationContext context;
public UserService(){
// context = new ClassPathXmlApplicationContext("META-INF/spring/application-context.xml");
}
public void closeApp(){
//context.close();
}
public void insert(){
//userRepository = context.getBean(UserRepository.class);
System.out.println("user vvvv");
User u = new User();
u.firstname="dede";
userRepository.save(u);
System.out.println("user eklendi");
ApplicationContext file from external jar file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.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">
<!-- JPA -->
<context:property-placeholder
location="/META-INF/spring/database.properties" />
<import resource="/database.xml"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
<property name="database" value="MYSQL" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<jpa:repositories base-package="org.springframework.data.example.jpa" />
Parent Project Package File
package abcdef;
import org.springframework.data.example.*;
import org.springframework.data.example.jpa.UserService;
import org.springframework.data.example.jpa.UserService2;
public class abcde {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserService u= new UserService();
u.insert();
}
}
ApplicationContext file from parent project
<!-- JPA -->
<context:property-placeholder
location="/META-INF/spring/database.properties" />
<import resource="/database.xml"/>
<import resource="classpath*:/META-INF/spring/*.xml" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
<property name="database" value="MYSQL" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>
<jpa:repositories base-package="org.springframework.data.example.jpa" />
After we run parent project's code i got the below error:
user vvvv
Exception in thread "main" java.lang.NullPointerException
at org.springframework.data.example.jpa.UserService.insert(UserService.java:47)
at abcdef.abcde.main(abcde.java:13)
Pretty simple. Your UserService isn't wired because you created it with new and didn't retrieved it from the spring context.
public class abcde {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("META-INF/spring/application-context.xml");
UserService u = ctx.getBean("userService");
u.insert();
}
}
or something like that.
However your UserService is lacking its xml configuration or the #Component and depending configuration that spring would actually wire it. You should probably create your local spring configuration file that imports the one from the external jar.

Debugging "Injection of autowired dependencies failed" Error in Spring+Hibernate

I have just started with Spring Framework and trying to develop and run a simple a app using Spring + Hibernate + Maven for dependency management.
I have a ContactController in which a property of type ContactService is Autowired. But when i packaged it into war and deployed on tomcat it throws a org.springframework.beans.factory.BeanCreationException with following messages :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]:
Invocation of init method failed; nested exception is org.hibernate.MappingException:
An AnnotationConfiguration instance is required to use <mapping
class="org.kodeplay.contact.form.Contact"/>
So I commented out that property from the ContactController Class along with all its references and re deployed it. But still it shows the same error.
This is the only controller in the entire application and an object implementing the ContactService interface is not being used any where else.
Whats going on here ? Am I missing something ?
Edit : Adding the code for spring-servlet.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
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.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config/>
<context:component-scan base-package="org.kodeplay.contact" />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Internationalization -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!-- To load database connection details from jdbc.properties file -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<!-- To establish a connection to the database -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<!-- Hibernate configuration -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>org.kodeplay.contact.form.Contact</value>
</list>
</property>
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
code for hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="org.kodeplay.contact.form.Contact" />
</session-factory>
</hibernate-configuration>
Thanks
I suspect this be a clash between AnnotationSessionFactoryBean and hibernate.cfg.xml. If you're using the former, you shouldn't need the latter. If you use both, you're going to have to duplicate some settings, and the cfg file might be eclipsing the Spring config.
Whatever you have in hibernate.cfg.xml you should be able to move into the bean definition for the AnnotationSessionFactoryBean, and that should resolve your error.
I guess you try to configure Hibernate with org.springframework.orm.hibernate3.LocalSessionFactoryBean. However, you use annotations in Hibernate mapping, therefore you need to use org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean instead.

Categories

Resources