Spring MVC project cannot use Hibernate - java

I want to build a Spring MVC project with Hibernate.
The IDE I used is Eclipse 4.4.2(Luna) and I installed the plugin Spring Tool Suite (STS) for Eclipse Luna (4.4).
The project I create is Spring project > Spring MVC Project.
Here is the External Jars I add :
antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.9.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
mysql-connector-java-5.0.8-bin.jar
Then, I add the detail of my database into /src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml :
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://192.168.1.43/MyDatabase" />
<beans:property name="username" value="testUser" />
<beans:property name="password" value="thePassOfTheUser" />
</beans:bean>
However, it shows the error message :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
org.springframework.jdbc.datasource.AbstractDataSource.<init>(AbstractDataSource.java:37)
org.springframework.jdbc.datasource.DriverManagerDataSource.<init>(DriverManagerDataSource.java:87)
Since I cannot fix it, I tried write hibernate.cfg.xml, but I have no idea where the file should be put.
I want to know how to set the bean to let my project can use Hibernate and how to use transitional way of hibernate (hibernate.cfg.xml) in the MVC project.
May 19th added
I found the solution.
It is because maven didn't load hibernate. Therefore after adding the following code into pom.xml it can work:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager‌​</artifactId>
<version>3.6.0.Final</version>
</dependency>
<dependency>
<groupId>org.‌​hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.0.Final</v‌​ersion>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</‌​artifactId>
<version>1.3.156</version>
</dependency>
<dependency>
<groupId>org.spring‌​framework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.0.6.RELEASE</ve‌​rsion>
</dependency>

Your error is related to missing library in classpath. Which is:
org.apache.commons.logging
Try to fix that first then tell if problem still occurs.

The stacktrace says that you're missing LogFactory which is part of Apache Commons Logging. I don't see it included in your external jars.
For the transitional way of hibernate create hibernate.cfg.xml configuration file and place it in the root of your application's classpath.
The XML configuration file must conform to the Hibernate 3 Configuration DTD, which is available from http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.
Here is a tutorial on it.

Related

Initialization of bean failed; ConversionNotSupportedException

I have a higher hierarchy context, which on server startup (tomcat) gets the following bean:
<bean id="org.sakaiproject.rubrics.api.rubric.RubricsService" class="org.sakaiproject.rubrics.impl.RubricsServiceImpl"
init-method="init"
singleton="true">
<property name="rubricsLogic" ref="org.sakaiproject.rubrics.logic.RURubricLogic" />
<property name="externalLogic" ref="org.sakaiproject.rubrics.api.rubric.ExternalLogic" />
</bean>
That bean's class ('RubricsServiceImpl'), implements an API interface called RubricsService ... so far so good. This initializes OK.
Down the hierarchy, when webapps are being deployed, on of these references this bean in applicationContext.xml :
<bean id="org.sakaiproject.rubrics.tool.RubricsTool" class="org.sakaiproject.rubrics.tool.RubricsTool">
<property name="rubricsService" ref="org.sakaiproject.rubrics.api.rubric.RubricsService" />
</bean>
While deploying the app, the following exception is thrown:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.sakaiproject.rubrics.tool.RubricsTool' defined in ServletContext resource [/WEB-INF/applicationContext.xml]:
Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.sakaiproject.rubrics.impl.RubricsServiceImpl' to required type 'org.sakaiproject.rubrics.api.rubric.RubricsService' for property 'rubricsService'; nested exception is java.lang.IllegalStateException:
Cannot convert value of type [org.sakaiproject.rubrics.impl.RubricsServiceImpl] to required type [org.sakaiproject.rubrics.api.rubric.RubricsService] for property 'rubricsService':
no matching editors or conversion strategy found
All the poms contain all the dependencies where they belong so no package starves from definitions or anything. I am clueless.
Could this be a Class Loader issue?
The following is my applications structure:
Ok... it was a classloader problem. The webapp's classloader was colliding with the container-level one, hence no casting could be done.
All the API .jars are deployed to tomcat's shared/lib directory for all apps to be able to access them. This is done by setting in the pom of the API module (of the webapp) :
<properties>
<deploy.target>shared</deploy.target>
</properties>
Now, based on the hierarchy of the webapp above, rubrics has a base pom.xml for the webapp, and in this, it is necessary to define the property so all the children poms of its modules, shared this dependencies. By markind in the base pom.xml of the webapp the following:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.sakaiproject.rubrics</groupId>
<artifactId>rubrics-api</artifactId>
<version>10.4</version>
<scope>provided</scope> <!-- from the CONTAINER -->
</dependency>
<dependency>
<groupId>org.sakaiproject.rubrics</groupId>
<artifactId>rubrics-impl</artifactId>
<version>10.4</version>
</dependency>
</dependencies>
</dependencyManagement>
Then, we just set the dependency if we need it with no .jar defined for that classloader, but to be provided by the container later on.
This was my interpretation after solving the issue. Please feel free to correct/add/enrich.

How to use TomEE with Hibernate

I have created very simple app with persistence context (hibernate as provider) to read some value from database. I use Eclipse with Maven.
First, I get
Caused by: org.apache.openejb.OpenEJBException: java.lang.ClassCastException: org.hibernate.ejb.HibernatePersistence cannot be cast to javax.persistence.spi.PersistenceProvider:
and according to this topic
http://openejb.979440.n4.nabble.com/problem-with-hibernate-persistence-provider-td980429.html
I excluded hibernate-jpa-2.0-api. Now, my dependencies look
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.3.Final</version>
<exclusions>
<exclusion>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
</exclusion>
</exclusions>
</dependency>
Now, I don't know why...
Caused by: java.lang.ClassNotFoundException: org.hibernate.transaction.TransactionManagerLookup
But TransactionManagerLookup is in hibernate-core.
Please, can anybody tell me, how should look pom.xml to use hibernate in TomEE?
1. Copy the required Hibernate .jars to <tomee-home>/lib
According to the documentation ( http://tomee.apache.org/tomee-and-hibernate.html ), the following ones are sufficient and in fact they worked for me:
<tomee-home>/lib/antlr-2.7.7.jar
<tomee-home>/lib/dom4j-1.6.1.jar
<tomee-home>/lib/hibernate-commons-annotations-4.0.2.Final.jar
<tomee-home>/lib/hibernate-core-4.2.21.Final.jar
<tomee-home>/lib/hibernate-entitymanager-4.2.21.Final.jar
<tomee-home>/lib/hibernate-validator-4.3.2.Final.jar
<tomee-home>/lib/javassist-3.18.1-GA.jar
<tomee-home>/lib/jboss-logging-3.1.0.GA.jar
All these .jars are contained in the Hibernate ORM 4.2.x download ( http://hibernate.org/orm/ ), except for the Hibernate Validator, which is a separate download ( http://hibernate.org/validator/ ).
2. Edit your pom.xml
Using the javaee-api maven artifact with a scope of provided you can now use the JPA specification in your project. However, if you have been using some Hibernate specific features, classes or annotations before, you can still refer to Hibernate in your pom.xml to match those dependencies:
<!-- JPA spec (required) -->
<dependencies>
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0-4</version>
<scope>provided</scope>
</dependency>
<!-- Hibernate specific features (only if needed) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.21.Final</version>
<scope>provided</scope>
</dependency>
3. Define your database connection
Edit <tomee-home>/conf/tomee.xml:
<Resource id="myJtaDatabase" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/my_dbname?autoReconnect=true
UserName foo
Password bar
validationQuery = SELECT 1
JtaManaged true
</Resource>
You can also put the above <Resource>...</Resource> definition into WEB-INF/resources.xml and ship it with your application instead:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<!-- Put <Resource> elements here -->
<resources>
4. JTA Datasource
Now that you told TomEE how to establish a connection, define a JTA datasource in /src/main/java/META-INF/persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
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">
<persistence-unit name="my_persistence_unit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:openejb/Resource/myJtaDatabase</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<!-- As many hibernate properties as you need, some examples: -->
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<!-- Drop and then re-create the database schema (don't do this in production) -->
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
5. Start using JPA
Obtain an EntityManager in a CDI bean or EJB like this:
#PersistenceContext(unitName = "my_persistence_unit")
private EntityManager em;
Final Notes
Hibernate versions 4.3+
I am using Hibernate 4.2.21 (JPA 2.0, Java EE 6) along with TomEE 1.7.2. Any TomEE 1.7.x, 1.6.x and 1.5.x will work. However, you cannot use Hibernate 4.3+ (JPA 2.1 / Java EE 7), as TomEE 1.7.x and below only support Java EE 6. If you really want to use Java EE 7 features along with TomEE, this blog post might be helpful: http://rmannibucau.wordpress.com/2013/07/19/little-tip-to-help-you-to-test-javaee-7-in-tomee-with-tomee-maven-plugin/
TomEE 1.5.x
TomEE 1.5.x already includes a javassist-<version>.jar, so you don't have to copy one.
Try this:
Add:
<tomee-home>/lib/antlr-2.7.7.jar
<tomee-home>/lib/dom4j-1.6.1.jar
<tomee-home>/lib/ehcache-core-2.5.1.jar
<tomee-home>/lib/ehcache-terracotta-2.5.1.jar
<tomee-home>/lib/hibernate-commons-annotations-4.0.1.Final.jar
<tomee-home>/lib/hibernate-core-4.1.4.Final.jar
<tomee-home>/lib/hibernate-ehcache-4.1.4.Final.jar
<tomee-home>/lib/hibernate-entitymanager-4.1.4.Final.jar
<tomee-home>/lib/hibernate-validator-4.3.0.Final.jar
<tomee-home>/lib/jboss-logging-3.1.0.GA.jar
<tomee-home>/lib/terracotta-toolkit-1.4-runtime-4.1.0.jar
The ehcache jars might be optional, but haven't tried without them.
Remove (optional):
<tomee-home>/lib/asm-3.2.jar
<tomee-home>/lib/bval-core-0.4.jar
<tomee-home>/lib/bval-jsr303-0.4.jar
<tomee-home>/lib/commons-lang-2.6.jar
<tomee-home>/lib/openjpa-2.2.0.jar
<tomee-home>/lib/serp-1.13.1.jar
yes just dropping the hibernate-jpa-2.1-api-1.0.0.Final.jar into the TomEE lib folder worked for me.

Spring 3.1, Hibernate 4, SessionFactory

This was working:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
...
but upgrading to the aforementioned versions breaks it. What is the correct method to create a SessionFactory bean with Spring 3.1.Release and Hibernate 4.0.0.FINAL?
The error on deploy is:
nested exception is java.lang.NoClassDefFoundError:
Lorg/hibernate/cache/CacheProvider;
EDIT
Have added my own answer, which fixed it for me.
I think you should use org.springframework.orm.hibernate4.LocalSessionFactoryBean instead of
org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
From LocalSessionFactoryBean javadoc:
NOTE: This variant of LocalSessionFactoryBean requires Hibernate 4.0 or higher. It is similar in role to the same-named class in the orm.hibernate3 package. However, in practice, it is closer to AnnotationSessionFactoryBean since its core purpose is to bootstrap a SessionFactory from annotation scanning.
Hibernate 4 has removed the deprecated CacheProvider-related interfaces and classes in favor of the previously released RegionFactory-related cache interface. You can find the version 4 cache package summary here, the version 3.2 cache package summary here (just before the RegionFactory interface was added) and the version 3.3 cache package summary here (when RegionFactory was first released).
Other than the JavaDoc, you might find the following documentation useful:
Using JBoss Cache as a Hibernate Second Level Cache - Chapter 5. Architecture
Ehcache Hibernate Second-Level Cache
Hibernate 4 - The Second Level Cache
However, based on the Spring 3.1 dependencies Spring 3.1 does not require Hibernate 4 (under the Full Dependencies section, JBoss Hibernate Object-Relational Mapper is at version 3.3.2.GA). If you want to upgrade to Hibernate 4, you'll need to update your cache settings. Otherwise, try using Hibernate 3.3.2 or higher 3.X version instead.
UPDATE: Keep in mind, Hibernate 4 documentation in Spring 3.1 is currently sparse. The Spring Framework Reference Documentation only has the following for Support for Hibernate 4.x:
See Javadoc for classes within the new org.springframework.orm.hibernate4 package
Spring 3.1 introduces the LocalSessionFactoryBuilder, which extends Hibernate's Configuration.
It would seem you should keep an eye out for some other changes if you want to use Hibernate 4.
UPDATE 2: Just noticed this question is a close duplicate of Exception NoClassDefFoundError for CacheProvider.
Use this configuration
hibernate configuration file:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
POM:
<!-- CGLIB -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>${cglib-version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${org.hibernate-version}</version>
<!-- will come with Hibernate core -->
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
i forgot to include the versions, I am using hibernate version: 4.1.2.Final and spring version: 3.1.1.RELEASE, there is an update of hibernate 4.1.3.Final, not tested but I believe it will work fine.
I had to change a couple of things, here we go :
In my transaction manager set up changed 3 -> 4 :
org.springframework.orm.hibernate4.HibernateTransactionManager;
And my sessionFactory to this (thanks #toxin) :
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
In the case of Hibernate 4.0 or higher, as of Spring 4.0, you should use
org.springframework.orm.hibernate4.LocalSessionFactoryBean
For example:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
...
</bean>
See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/orm/hibernate4/LocalSessionFactoryBean.html
In the case of Hibernate 5.0/5.1/5.2, as of Spring 4.3, you should better instead use
org.springframework.orm.hibernate5.LocalSessionFactoryBean
(See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/orm/hibernate5/LocalSessionFactoryBean.html)
Spring 3.1 and Hibernate 4 are not compatible in so many ways. Please refer the following Spring JIRA https://jira.springsource.org/browse/SPR-9365

java.lang.NoClassDefFoundError for my DAO

i am using spring.xml for my controller and dao configuration. my spring-config.xml is as below:
<bean id="courseDao" class="com.platysgroup.lmex.adapter.moodle.dao.CourseDao"
init-method="setMoodleDataSource" depends-on="moodleAuthenticationDetails">
<property name="adapterDataSource" ref="adapterDataSource"></property>
<property name="userDao" ref="userDao"></property>
<property name="announcementDao" ref="announcementDao"></property>
<property name="roleDao" ref="roleDao"></property>
<property name="logDao" ref="logDao"></property>
</bean>
i have a coursedao class in my project in the package com.platysgroup.lmex.adapter.moodle.dao in the project name lmex-impl. but my spring config is not getting the class from a lmex-impl.jar. the spring-config.xml is on lmex-web project. and other thing is that he is showing me a wrong path in exception. the wrong name is Lcom/platysgroup/lmex/adapter/moodle/dao/CourseDao; instead of com/platysgroup/lmex/adapter/moodle/dao/CourseDao; the exception full stacktrace is as below:
javax.servlet.ServletException: Servlet.init() for servlet Spring MVC Dispatcher Servlet threw exception
org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:195)
org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:159)
org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:141)
org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:90)
org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:417)
root cause
java.lang.NoClassDefFoundError: Lcom/platysgroup/lmex/adapter/moodle/dao/CourseDao;
java.lang.Class.getDeclaredFields0(Native Method)
java.lang.Class.privateGetDeclaredFields(Class.java:2291)
java.lang.Class.getDeclaredFields(Class.java:1743)
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.findResourceMetadata(CommonAnnotationBeanPostProcessor.java:315)
org.springframework.context.annotation.CommonAnnotation.........
java.lang.ClassNotFoundException: com.platysgroup.lmex.adapter.moodle.dao.CourseDao
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
please help me to resolve this.
Thank you
A NoClassDefFoundError is thrown when the JRE can't find a class. In your case, it can't find the class Lcom/platysgroup/lmex/adapter/moodle/dao/CourseDao, which you most probably did not add to your classpath.
The prefix 'L' indicates the instance of class. Please see Field Descriptors. You should focus on finding issue with configuration of bean courseDao and check that its all dependencies are there in same application context.

Spring & hibernate configuration (using maven): java.lang.ClassNotFoundException: org.hibernate.cfg.Configuration

I am trying to include spring and hibernate in an application running on a Weblogic 10.3 server. When I run the application in the server, while accessing an TestServlet to check my configuration I get the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySessionFactory' defined in class path resource [spring-config/HorizonModelPeopleConnectionsSpringContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org.hibernate.cfg.Configuration
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:448)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:284)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:91)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:75)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:65)
at view.com.horizon.test.SpringHibernateServlet.doGet(SpringHibernateServlet.java:27)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.security.wls.filter.SSOSessionSynchronizationFilter.doFilter(SSOSessionSynchronizationFilter.java:279)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.dms.wls.DMSServletFilter.doFilter(DMSServletFilter.java:326)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3592)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2202)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2108)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1432)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org.hibernate.cfg.Configuration
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:100)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:61)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:756)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:721)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:384)
... 31 more
Caused by: java.lang.NoClassDefFoundError: org.hibernate.cfg.Configuration
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.class$(LocalSessionFactoryBean.java:158)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.(LocalSessionFactoryBean.java:158)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:85)
... 35 more
I have checked my application and the hibernate jar file is included and it contains the class it says its missing: org.hibernate.cfg.Configuration.
The application is built with maven. These are the dependencies of the JAR file using spring and hibernate:
<!-- Frameworks -->
<!-- Hibernate framework -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.7.ga</version>
</dependency>
<!-- Hibernate uses slf4j for logging, for our purposes here use the simple backend -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.2</version>
</dependency>
<!-- Hibernate gives you a choice of bytecode providers between cglib and javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.4.GA</version>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>2.5.6</version>
</dependency>
At first I thought it could be an issue with the versions in the spring and hibernate libraries, so I have tried with different ones, but still I couldn't find anywhere where it says which library versions are compatible,. just got that Spring 2.5.x needs hibernate >=3.1
And this is my Spring config file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd">
<bean id="myDataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/WebCenterDS</value>
</property>
<!--property name="resourceRef">
<value>true</value>
</property>
<property name="jndiEnvironment">
<props>
<prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
<prop key="java.naming.provider.url">t3://localhost:7001</prop>
</props>
</property-->
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="configLocation">
<value>classpath:hibernate-config/hibernate.cfg.xml</value>
</property>
<property name="mappingResources">
<list>
<value>classpath:com/horizon/model/peopleconnections/profile/internal/bean/CustomAttribute.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value>
</property>
</bean>
<bean id="profileExtensionDAO"
class="com.horizon.model.peopleconnections.profile.internal.dao.ProfileExtensionDAOImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
</beans>
The WAR structure I get is the following:
J2EETestApplication
│ springhibernate.jsp
│
└───WEB-INF
│ faces-config.xml
│ web.xml
│ weblogic.xml
│
├───classes
│ └───view
│ └───com
│ └───horizon
│ └───test
│ SpringHibernateServlet.class
│
└───lib
activation-1.1.jar
antlr-2.7.6.jar
aopalliance-1.0.jar
asm-1.5.3.jar
asm-attrs-1.5.3.jar
cglib-2.1_3.jar
commons-codec-1.3.jar
commons-collections-2.1.1.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
hibernate-3.2.7.ga.jar
horizon-model-commons-1.0-SNAPSHOT.jar
horizon-model-peopleconnections-1.0-SNAPSHOT.jar
horizon-shared-commons-1.0-SNAPSHOT.jar
horizon-shared-logging-1.0-SNAPSHOT.jar
horizon-shared-util-1.0-SNAPSHOT.jar
horizon-shared-webcenter-1.0-SNAPSHOT.jar
horizon-shared-webcenter.jar
httpclient-4.0.1.jar
httpcore-4.0.1.jar
javassist-3.4.GA.jar
jta-1.0.1B.jar
log4j-1.2.14.jar
mail-1.4.1.jar
peopleconnections-profile-model-11.1.1.2.0.jar
saxon-9.1.0.8.jar
serviceframework-11.1.1.2.0.jar
slf4j-api-1.5.2.jar
slf4j-log4j12-1.5.2.jar
spring-beans-2.5.6.jar
spring-context-2.5.6.jar
spring-core-2.5.6.jar
spring-orm-2.5.6.jar
spring-tx-2.5.6.jar
Is there any dependency or configuration I am missing?
If I use hibernate without spring using (with the same libraries) I don't get the ClassDefNotFoundException:
import java.net.URL;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
URL hibernateConfigURL = HibernateUtil.class.getClassLoader().getResource("hibernate-config/hibernate.cfg.xml");
return new Configuration().configure(hibernateConfigURL).buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
That makes me think that is not a problem with the hibernate library not being properly picked. The Spring libraries seem to be picked properly as it starts to build the beans from the ApplicationContent. Could it be an issue of these two libraries not seeing each other?
My guess is that your application is not using the Spring JARs inside the webapp but the one provided by WebLogic and those can't "see" the Hibernate JAR inside the war.
To tell Weblogic to look into the war file, provide a WEB-INF/weblogic.xml with prefer-web-inf-classes set to true (this is required for Hibernate anyway because of the ANTLR version bundled in WLS):
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://www.bea.com/ns/weblogic/90" xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/90 http://www.bea.com/ns/weblogic/90/weblogic-web-app.xsd">
<context-root>/myApp</context-root>
<container-descriptor>
<prefer-web-inf-classes>true</prefer-web-inf-classes>
</container-descriptor>
</weblogic-web-app>
You have missed the hibernate-core dependency...example in the docs.
http://docs.jboss.org/hibernate/stable/core/reference/en/html/tutorial.html#tutorial-firstapp-mvn
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
i had compile 'org.hibernate:hibernate-core:4.1.9'
i replaced it with compile 'org.hibernate:hibernate-core:3.3.2.GA'
this is gradle syntax, converting to maven isnt difficult
In addition to your answer #Rafeeq, this did the trick should incase you are using Maven dependency on pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
</dependency>

Categories

Resources