I am trying to integrate spring with hibernate this morning. I want to use spring transaction manager. But getting the below error. The error has something to do with #Trasactional Annotation. If i remove the annotation,im able to get the bean from the spring container.
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy19 cannot be cast to com.hibernate.dao.EvntDAOImpl
at com.hibernate.action.HibernateAction.main(HibernateAction.java:17)
Im pasting below my source code.
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>hibernate-tutorials</groupId>
<artifactId>hibernate-tutorials</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring-framework.version>4.0.3.RELEASE</spring-framework.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring ORM support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.2.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
Hibernate Configuration
<?xml version="1.0" encoding="UTF-8"?>
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.hibernate.model.Evnt</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernatey.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
EvntDAOImpl.java
package com.hibernate.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.hibernate.model.Evnt;
#Repository(value="evntDAO")
#Transactional
public class EvntDAOImpl implements EvntDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public void storeEvnt(Evnt evnt) {
sessionFactory.getCurrentSession().save(evnt);
}
}
HibernateAction.java
package com.hibernate.action;
import java.util.Date;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hibernate.dao.EvntDAO;
import com.hibernate.dao.EvntDAOImpl;
import com.hibernate.model.Evnt;
public class HibernateAction {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
EvntDAOImpl evntDAO = (EvntDAOImpl) context.getBean("evntDAO");
Evnt evnt = new Evnt();
evnt.setTitle("first Event");
evnt.setDate(new Date());
evntDAO.storeEvnt(evnt);
}
}
Thanks in advance...
The problem is in the place where you are injecting EventDaoImpl.
Just replace
#Autowired EventDaoImpl eventDaoImpl
with
#Autowired EventDao eventDao
wherever you need Spring to autowire the dao.
Or if you are getting the bean from the applicationContext use:
EvntDAO evntDAO = (EvntDAO) context.getBean("evntDAO");
The problem is caused by the fact that the use of #Transactional annotation on the dao's implementation code means that Spring will create a JDK dynamic proxy for it, which cannot be cast to the implementation class. Here is the complete documentation of Spring's AOP capabilities (where the creation of JDK dynamic proxies and CGLib class proxies is fully explained).
What that essentially means is that because of #Transactional, when you call context.getBean("evntDAO") you don't get back your EventDaoImpl (as one would expect), but you actually get back an object whose class is java.lang.reflect.Proxy which has been created by Spring. That proxy object implements EventDao (and therefor can be cast to it) but it's signature has nothing to do with EventDaoImpl (and hence the ClassCastException since it does not extend EventDaoImpl). When a method is called on the proxy various things happen before and/or after the call is actually delegated to EventDaoImpl (what happens before/and or after the actual call to EventDaoImpl is controlled by Spring though the implementation of InvocationHandler).
Related
I want to set session factory in DAO class but after execution I got this issue. In my class i am setting sessionFactory variable through #Autowired annotation but it is not able to set the session Factory.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field sessionFactory in com.springboot.webcrud.dao.ClienteDao required a bean of type 'org.hibernate.SessionFactory' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.
Process finished with exit code 1
WHEN I REMOVE THE #Autowired ANNOTATION THEN THE SESSION FACTORY IS ALWAYS NULL WHEN I TRY TO GET THE CURRENT SESSION
This is my project structure: project structure
pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springboot</groupId>
<artifactId>webcrud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mvc</name>
<packaging>war</packaging>
<description>WEB CRUD</description>
<properties>
<java.version>16</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--Dependencias de desarrollo -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
<!--Dependencias base de datos -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties file
I'm not able to serve the jsp files without declaring this in the properties file. I fear the hibernate configuration is not properly set since the servlet.xml file seems not to be enough. I don't get why the servlet.xml file is not enough
spring.mvc.view.prefix = /WEB-INF/jsp/
spring.mvc.view.suffix = .jsp
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>MVC APP</display-name>
<absolute-ordering />
<!-- Configuracion del dispatcher servlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Ubicacion URL del servlet -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
servlet.xml 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"
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">
<!-- Paquete de escaneo de componentes -->
<context:component-scan base-package="com.springboot.webcrud"/>
<!-- Conversión formateo y validación-->
<mvc:annotation-driven/>
<!-- Configuración Spring MVC directorio view -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- Origen BBDD y connection pool -->
<bean id="dataSource" name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/tienda?useSSL=false&serverTimezone=UTC"/>
<property name="user" value="root"/>
<property name="password" value="BaseDeDatos2022"/>
<!-- Propiedades connection pool para C3P0 -->
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="20"/>
<property name="maxIdleTime" value="30000"/>
</bean>
<!-- Configuración Hibernate session factory -->
<bean id="sessionFactory" name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.springboot.webcrud.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="ClienteDao" name="ClienteDao" class="com.springboot.webcrud.dao.ClienteDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateTemplate" name="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Configuración Hibernate transaction manager -->
<bean id="txManager" name="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Habilitar configuración de transacciones basadas en anotaciones -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
Entity class
package com.springboot.webcrud.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
#Setter
#Getter
#ToString
#Entity
#Table(name = "clientes")
public class Cliente {
public Cliente() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
String id;
#Column(name = "nombre")
String nombre;
#Column(name = "apellido")
String apellido;
#Column(name = "email")
String email;
}
DAO Class
When I remove the #Autowired annotation then the sessionFactory is always null when I try to get the current session
package com.springboot.webcrud.dao;
import com.springboot.webcrud.entity.Cliente;
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 javax.transaction.Transactional;
import java.util.List;
#Repository
public class ClienteDao implements IClienteDao {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Cliente> listarClientes() {
if (sessionFactory == null) {
System.out.println("SESION NULA");
return null;
}
Session session = sessionFactory.getCurrentSession();
System.out.println("SESION OK");
Query<Cliente> query = session.createQuery("from Cliente", Cliente.class);
return query.getResultList();
}
}
Controller class
package com.springboot.webcrud.controller;
import com.springboot.webcrud.dao.IClienteDao;
import com.springboot.webcrud.entity.Cliente;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
#Controller
#RequestMapping("/tienda")
public class TiendaController {
#Autowired
IClienteDao servicioCliente;
#RequestMapping("/clientes")
public String listarClientes(Model model) {
System.out.println("Página de clientes");
List<Cliente> clientes = servicioCliente.listarClientes();
model.addAttribute("clientes", clientes);
for (Cliente cliente : clientes
) {
System.out.println(cliente.toString());
}
return "listaClientes";
}
}
Please I appreciate your help I've been stuck here for several days.
I am newbie to Spring & Hibernate,
Trying to run project that run them togethet.
After a lot of error fixing the things work well,
But when I'm running the main class I still get that exception :
org.hibernate.HibernateException: Use of DefaultSchemaNameResolver requires Dialect to provide the proper SQL statement/command but provided Dialect [org.hibernate.dialect.MySQL57Dialect] did not return anything from Dialect#getCurrentSchemaCommand
at org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver$SchemaNameResolverFallbackDelegate.resolveSchemaName(DefaultSchemaNameResolver.java:100) ~[hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver.resolveSchemaName(DefaultSchemaNameResolver.java:76) ~[hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.determineCurrentSchemaName(JdbcEnvironmentImpl.java:298) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:232) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:179) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:84) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:474) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724) [hibernate-core-5.3.1.Final.jar:5.3.1.Final]
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:343) [spring-orm-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:431) [spring-orm-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:416) [spring-orm-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) [spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) [spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) [spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) [spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) [spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) [spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) [spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753) [spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) [spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) [spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) [spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) [spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at springboot.beans.app.SpringHibernateMain.main(SpringHibernateMain.java:24) [classes/:na]
Trying google it, to remove the dialect property, or change it, but it's not work.
What is the cause of it, and how to fix (also getting a lot of warnings ate the pom.xml about versions overriding).
This is the relevant files, I hope:
The running class:
package springboot.beans.app;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import database.ManageEmployee;
import withAnnotation.InsertRecords;
import withAnnotation.InsertRecords2;
import withAnnotation.Product;
public class SpringHibernateMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("SpringHibernateConfiguration.xml");
ManageEmployee manager = context.getBean(ManageEmployee.class);
/* Add few employee records in database */
Integer empID1 = manager.addEmployee("Spring222", "TODAY222", 30000);
Integer empID2 = manager.addEmployee("Avraham-spring", "Das", 5000);
Integer empID3 = manager.addEmployee("Sarah wigh spring", "Paul", 10000);
/* List down all the employees */
manager.listEmployees();
/* Update employee's records */
manager.updateEmployee(empID1, 5000);
System.out.println(empID2 + " = empID2");
/* Delete an employee from the database */
manager.deleteEmployee(empID2);
/* List down new list of the employees */
manager.listEmployees();
InsertRecords2 producer = context.getBean(InsertRecords2.class);
producer.updateProducts();//it's running insertion from inside
System.out.println("check if done");
//close resources
context.close();
}
}
The SpringHibernateConfiguration.xml :
<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: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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<!-- <property name = "hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
-->
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/hibernate_mysql7?useSSL=false" />
<property name="username" value="XXXX" />
<property name="password" value="XXXX" />
</bean>
<!-- Hibernate 3 XML SessionFactory Bean definition-->
<!-- <bean id="hibernate3SessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean> -->
<!-- Hibernate 4 Annotation SessionFactory Bean definition-->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses"><!-- sessionFactory -->
<list>
<!-- <value>Employee.hbm.xml</value> ? <value>database.Employee</value> -->
<value>withAnnotation.Product</value>
</list>
</property>
<!-- add this -->
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
<!-- end -->
<property name="hibernateProperties">
<props>
<!-- this cause new creating and clean all from the past
<prop key="hibernate.hbm2ddl.auto">create</prop>
if u want to create once and keep use that instead :-->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- hibernate found it by itself <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> -->
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop><!-- <property name="hibernate.hbm2ddl.auto">create</property> -->
</props>
</property>
</bean>
<bean id="managerEmployee" class="database.ManageEmployee">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
<bean id="producer" class="withAnnotation.InsertRecords2">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</bean>
</beans>
the pom.xml :
<
project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springboot.beans.app</groupId>
<artifactId>SpringHibernateBasic5-OtherConfiguration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringHibernateBasic5-OtherConfiguration</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.2.7.RELEASE</spring.version>
<java.version>1.8</java.version>
<spring-framework.version>4.0.3.RELEASE</spring-framework.version>
<!-- *** added -->
<!-- Hibernate / JPA -->
<!-- <hibernate.version>4.3.5.Final</hibernate.version> -->
<hibernate.version>5.3.1.Final</hibernate.version> <!-- 3.6.9.Final-->
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<!-- Spring boot dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring ORM support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Spring dependency -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The full log of the running is long , so what I need to copy here ?
There are several things flawed in your approach
Mixing 3 different Spring versions (5.0, 4.2 and 4.0)
Using a hibernate version that isn't supported by Spring 4
Use Hibernate 4 support classes to configure hibernate 5
Tried to use Spring Boot, stepped back and worked around it
Use Hibernate instead of JPA and Hibernate as the JPA provider
First of all clean up your pom.xml and use Spring Boots dependency management to your advantage.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springboot.beans.app</groupId>
<artifactId>SpringHibernateBasic5-OtherConfiguration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringHibernateBasic5-OtherConfiguration</name>
<url>http://maven.apache.org</url>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<!-- Spring boot dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Notice that most of your dependencies are gone as most of them are already managed by one of the starters you had (slf4j, logback, Spring dependencies). You want to use Hibernate (and I suggest to use JPA instead of plain hibernate) it is enough to add spring-boot-starter-data-jpa to get all the needed dependencies.
Next create an application.properties in src/main/resources and put the following in there (deducted from your question).
spring.datasource.url=jdbc:mysql://localhost:3306/hibernate_mysql7?useSSL=false
spring.datasource.username=XXXX
spring.datasource.password=XXXX
spring.jpa.hibernate.ddl-auto=update
This will configure the datasource and create the schema (although you are better not to use that in production!).
Now modify your SpringHibernateMain and put an #SpringBootApplication annotation on it and change your main method. Also place your entities in a proper sub package.
#SpringBootApplication
public class SpringHibernateMain {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(SpringHibernateMain.class ,args);
ManageEmployee manager = context.getBean(ManageEmployee.class);
/* Add few employee records in database */
Integer empID1 = manager.addEmployee("Spring222", "TODAY222", 30000);
Integer empID2 = manager.addEmployee("Avraham-spring", "Das", 5000);
Integer empID3 = manager.addEmployee("Sarah wigh spring", "Paul", 10000);
/* List down all the employees */
manager.listEmployees();
/* Update employee's records */
manager.updateEmployee(empID1, 5000);
System.out.println(empID2 + " = empID2");
/* Delete an employee from the database */
manager.deleteEmployee(empID2);
/* List down new list of the employees */
manager.listEmployees();
InsertRecords2 producer = context.getBean(InsertRecords2.class);
producer.updateProducts();//it's running insertion from inside
System.out.println("check if done");
}
}
Now place the SpringHibernateMain in a decent package like springboot.beans.app (as you had) and place the entities in springboot.beans.app.entities and everything else in springboot.beans.app.services (instead of what you have now).
The thing left for you is to "rewrite" your classes InsertRecords2 and ManageEmployee to use the EntityManager instead of the plain SessionFactory. It will still use Hibernate underneath but generally it is better to use JPA and only plain Hibernate in those cases you really need.
I'm using spring-5.0.3
http://localhost:8080/firstapp_spring/greeting
HTTP Status 500 - Internal Server Error
type Exception report
messageInternal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: No adapter for handler [com.actions.GreetingController#4275cbe5]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler
There is no error during building project.
pom.xml =>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
class=>
package com.actions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class GreetingController {
#RequestMapping(value = "/firstapp_spring/greeting", method = RequestMethod.GET)
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
return "greeting";
}
#RequestMapping(value = "/firstapp_spring/greeting", method = RequestMethod.POST)
public String greetingSubmit(#ModelAttribute Greeting greeting) {
return "result";
}
}
app-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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.ftl</value>
</property>
</bean>
<bean name="/hello" class="com.actions.HelloController"></bean>
<bean name="/greeting" class="com.actions.GreetingController"></bean>
</beans>
The request mapping that you've defined in your Controller class is:
#RequestMapping(value = "/firstapp_spring/greeting", method = RequestMethod.GET)
and the URL you're trying to access is:
http://localhost:8080/myproject/greeting
You're missing the "/firstapp_spring" part.
Since you're using Spring > 4.3 you can take advantage of the new HTTP mapping annotations: #GetMapping and #PostMapping
Your request mapping can become, the much shorter equivalent:
#GetMapping("/firstapp_spring/greeting")
I'm doing a GWTP project and use Spring Data JPA for a connection with an oracle database. I've read several tutorials in which a repository interface is used directly without the use of implementation. It was #Autowired where needed and it worked fine. I've tried to use the same strategy but it seems the #Autowired annotation is not working at all.
Here is my Repository :
#Repository
public interface BugRepository extends JpaRepository<Bug, Long> {
List<Bug> findAll();
.....
}
I try to inject it with #Autowired in my service implementation (I use RESTful services) :
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/bugs")
#Component
public class BugServiceImpl{
#Autowired
private BugRepository bugRepository;
#GET
#Path("/findAll")
public List<Bug> findAll() {
return bugRepository.findAll();
}
}
Here is my Entity :
#Entity
#Table(name = "BUGS")
#SequenceGenerator(name = "BUG_SEQUENCE", sequenceName = "BUG_SEQUENCE")
public class Bug implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "BUG_SEQUENCE")
#Column(name="BUG_ID")
private Long bugId;
#Column(name="BUG_NAME")
private String bugName;
#OneToOne
#PrimaryKeyJoinColumn
#Column(name="CREATED_BY")
private User createdBy;
#OneToOne
#PrimaryKeyJoinColumn
#Column(name="ASSIGNED_TO")
private User assignedTo;
#Column(name="CREATION_DATE")
private Date creationDate;
#Column(name="LAST_UPDATE_DATE")
private Date lastUpdateDate;
#Column(name="BUG_COMMENT")
private String bugComment;
#OneToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER, orphanRemoval = true)
#PrimaryKeyJoinColumn
#Column(name="PRIORITY_ID")
private Priority priority;
#OneToOne
#PrimaryKeyJoinColumn
private Status status;
public Bug() {
}
}
I also have applicationContext.xml and persistence.xml in main/resources/META-INF. Here is my 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:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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
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.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:component-scan base-package="com.edu" />
<jpa:repositories base-package="com.edu.server.repositories" />
<context:annotation-config />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="***"/>
<property name="username" value="***"/>
<property name="password" value="***"/>
</bean>
<!-- EntityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="com.edu.shared.entity"
p:dataSource-ref="dataSource"
>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="false" />
</bean>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
My persistence.xml :
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<!-- oracle -->
<persistence-unit name="oracle">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.edu.server.service.BugServiceImpl</class>
<class>com.edu.server.repositories.BugRepository</class>
<class>com.edu.shared.entity.Bug</class>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver" />
<property name="hibernate.connection.url" value="***" />
<property name="hibernate.connection.username" value="***" />
<property name="hibernate.connection.password" value="***" />
<property name="hibernate.flushMode" value="FLUSH_AUTO" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
And finally the exception I get is :
java.lang.NullPointerException
com.edu.server.service.BugServiceImpl.findAll(BugServiceImpl.java:39)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
...
When I debug the code and put a breakpoint to the autowired repository it appears to be null so I suppose it's not injected properly and that's why invoking the method findAll fires the NullPointerException. So, why do you think the #Autowired annotation is not working?
I think you're mixing two ways of Spring/JPA configuration. Last time when i configured Spring/JPA project with XML I use only DataSource bean without persistence.xml configuration for connection to the database. I can suggest you to read the official documentation of Spring Data. The community has one of the best documentation.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html
First problem that i see is you have annotated your interface with #Repository
You shouldn't do that, but as follows:
//no annotation here
public interface BugRepository extends JpaRepository<Bug, Long> {
List<Bug> findAll();
.....
}
Secondly, make sure your BugRepository interface is in the package below, or else it wont work:
<jpa:repositories base-package="com.edu.server.repositories" />
Third thing i noticed is in your persistance.xml, you have noted NOT only #Entity beans, but #Service and a #Repository. You are supposed to only have #Entity beans (which are to be managed)
Lastly, you seem to be mixing Spring and Jersey, so make sure you have your Spring container (application/web context) properly set up, so it can manage (inject) your beans/repos/services.
I want to thank all for the help. I solved my problem. There were problems in my configuration files.
First of all, I really didn't need any persistence.xml because I've created a dataSource bean in my applicationContext.xml which contains all of the needed information regarding the connection with my database. You shouldn't mix the both things, I suppose.
Secondly, you should properly configure the link between Spring and Jersey. I had to add some new dependencies in my pom.xml which were needed for linking Spring and Jersey (there is a jersey-spring3 dependency which I didn't know existed). So, now all of the dependencies I use, concerning Spring and Jersey are these:
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${javax.rs.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.fusesource.restygwt</groupId>
<artifactId>restygwt</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>1.1.2.RELEASE</version>
<type>pom</type>
<!--<scope>import</scope>-->
<scope>compile</scope>
</dependency>
<!-- DataSource (HikariCP) -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.2.5</version>
</dependency>
<!-- JPA Provider (Hibernate) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>12.1.0.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
</exclusions>
</dependency>
In addition, I had to configure my web.xml so that Jersey could read the applicationContext.xml. Without configuring my web.xml the applicationContext.xml was useless and that's why the annotations and the connection with the database didn't work. Here is my web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.edu</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
As far as I understood the ContextLoadListener makes sure the web configuration "listens" for other configuration xml files and that's how the applicationContext.xml is now read and used. And with these settings
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.edu</param-value>
I make sure that my packages would be scanned for #Provider and #Path annotations and without these piece of my code my services would not be active.
More about this Provider Packages setting can be read here :
https://jersey.java.net/apidocs/2.23.2/jersey/org/glassfish/jersey/server/ServerProperties.html#PROVIDER_PACKAGES
I hope my issue and this answer are useful for all with similar configuration problems.
Error occurred during deployment: Exception while loading the app :
java.lang.IllegalStateException: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException:
java.lang.IncompatibleClassChangeError: Implementing class. Please see server.log for more details.
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'helloWorldController':
Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private org.hibernate.SessionFactory
org.meluk.billboard.business.controller.HelloWorldController.sessionFactory; nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in
ServletContext resource [/WEB-INF/billboard-servlet.xml]:
Invocation of init method failed; nested exception is
java.lang.IncompatibleClassChangeError: Implementing class
My pom.xml:
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springVersion>3.1.0.RELEASE</springVersion>
<hibernateVersion>3.5.4-Final</hibernateVersion>
<junitVersion>4.8.2</junitVersion>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springVersion}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.sql</groupId>
<artifactId>jdbc-stdext</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junitVersion}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernateVersion}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernateVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-hibernate3</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springVersion}</version>
</dependency>
My spring config file:
<context:component-scan base-package="org.meluk.billboard.business.controller" />
<tx:annotation-driven transaction-manager="txManager" />
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/config/jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="${hibernate.connection.driver_class}" />
<property name="url" value="${hibernate.connection.url}" />
<property name="username" value="${hibernate.connection.username}" />
<property name="password" value="${hibernate.connection.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/WEB-INF/hibernate.cfg.xml" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.default_schema">${hibernate.default_schema}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.c3p0.min_size">${hibernate.c3p0.min_size}</prop>
<prop key="hibernate.c3p0.max_size">${hibernate.c3p0.max_size}</prop>
<prop key="hibernate.c3p0.timeout">${hibernate.c3p0.timeout}</prop>
<prop key="hibernate.c3p0.max_statements">${hibernate.c3p0.max_statements}</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Please help to resolve this issue.
You explicitly set a spring-hibernate3 dependency:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-hibernate3</artifactId>
<version>2.0.8</version>
It's not a coincidence that this is the bean you're getting the exception on.
You shouldn't need to do that; is there a reason you're not using spring-orm of the same version of Spring you're using? I haven't set an explicit hibernate3 dependency for quite some time.
An IncompatibleClassChangeError means that JVM is getting contradictory information about some class. This typically happens when you compile some code against one version of an class or interface, but then use a different version of that class / interface at runtime. The problem is picked up at runtime when the JVM checks that the class and method signatures match.
In this case, the "Implementing class" message seems to be saying that the class that changed no longer implements some interface that it did originally. (Maybe the package name changed.)
Somewhere in your log files there should be a message that names the classes that are causing the problem, but the expurgated versions of the stacktrace that you provided don't.
I'd say they are two possibilities. One is that you've got a problem with the way you are doing your builds, and that you are not recompiling things that ought to be recompiled. The other possibility is that you've got an inconsistent mix of JARs in your WAR file; e.g. you are somehow mixing JARs from different versions of Spring.