#Autowired does not inject Spring Data JPA Repository - NullPointerException - java

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.

Related

Not able to set session factory through servlet.xml using Spring MVC and Hibernate 5

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.

Spring-hibernate : How to solve HibernateException" DefaultSchemaNameResolver requires Dialect to provide MySQL5Dialect"

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.

Spring JDBC MVC project gives 404

I've been fighting with the Spring framework for few weeks now, and I got
a normal MVC page to show up, and I got JDBC to print onto the console.
But I can't seem to get these to work together...
I've been through countless tutorials at this point and every one of them
seem to have some type of error or problem.
I think I've finally managed to get together a pretty decent and working build, but nope, still getting only 404's.
I think the problem might be in the spring-servlet.xml file:
<context:component-scan base-package="src" />
And I'm not sure if you can even load project like that, but it's the only thing I can think of here.
I include all the other files too, though.
Console Errors
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:spring-mvc' did not find a matching property.
and
SEVERE: Servlet [spring] in web application [/spring-mvc] threw load() exception
java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1275)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1109)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1050)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4903)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5213)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
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>spring-mvc</groupId>
<artifactId>spring-mvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<java.version>1.8</java.version>
<spring.version>3.1.0.RELEASE</spring.version>
<cglib.version>2.2.2</cglib.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.gatein.common</groupId>
<artifactId>common-logging</artifactId>
<version>2.2.2.Final</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j</artifactId>
<version>2.8.1</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Telling container to take care of annotations stuff -->
<context:annotation-config />
<!-- Declaring base package -->
<context:component-scan base-package="controller" />
<!-- Adding view resolver to show jsp's on browser -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Declare beans -->
<bean id="userDao" class="dao.UserDaoImpl" />
<bean id="userService" class="services.UserServiceImpl" />
<!-- Declare datasource bean -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/userdb" />
<property name="username" value="root" />
<property name="password" value="38613861" />
</bean>
</beans>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>SpringJDBCTemplate</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
homePageController
package controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import domain.*;
import services.*;
#Controller
public class HomePageController {
#Autowired
UserService userService;
#RequestMapping("/register")
public ModelAndView registerUser(#ModelAttribute User user) {
List<String> genderList = new ArrayList<String>();
genderList.add("male");
genderList.add("female");
List<String> cityList = new ArrayList<String>();
cityList.add("delhi");
cityList.add("gurgaon");
cityList.add("meerut");
cityList.add("noida");
Map<String, List> map = new HashMap<String, List>();
map.put("genderList", genderList);
map.put("cityList", cityList);
return new ModelAndView("register", "map", map);
}
#RequestMapping("/insert")
public String inserData(#ModelAttribute User user) {
if (user != null)
userService.insertData(user);
return "redirect:/getList";
}
#RequestMapping("/getList")
public ModelAndView getUserLIst() {
List<User> userList = userService.getUserList();
return new ModelAndView("userList", "userList", userList);
}
#RequestMapping("/edit")
public ModelAndView editUser(#RequestParam String id,
#ModelAttribute User user) {
user = userService.getUser(id);
List<String> genderList = new ArrayList<String>();
genderList.add("male");
genderList.add("female");
List<String> cityList = new ArrayList<String>();
cityList.add("delhi");
cityList.add("gurgaon");
cityList.add("meerut");
cityList.add("noida");
Map<String, Object> map = new HashMap<String, Object>();
map.put("genderList", genderList);
map.put("cityList", cityList);
map.put("user", user);
return new ModelAndView("edit", "map", map);
}
#RequestMapping("/update")
public String updateUser(#ModelAttribute User user) {
userService.updateData(user);
return "redirect:/getList";
}
#RequestMapping("/delete")
public String deleteUser(#RequestParam String id) {
System.out.println("id = " + id);
userService.deleteData(id);
return "redirect:/getList";
}
}
Project tree
Project tree from Eclipse Neon2
Not my answer but the one which solved the case, posting as answers since it's buried deep in comments.
Sorry for the delay.... It still not right. I know that because
Eclipse should not show the package as main.java.controller.... Maven
ignores that folder and start right under the java folder as it was
the src folder itself. Something must be wrong on your project. Try
cleaning everything, remove the project from eclipse, delete
(physically) the folder .settings and the file .classpath and the file
.project. Go on your folder project on the console and run mvn clean
eclipse:clean then open all folders of if (like the image I showed to
you) and paste it here so I can see what it is wrong
– Jorge Campos

Using #Transactional annotation for hibernate application resulting in error

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).

java.lang.NoClassDefFoundError: org/hibernate/criterion/Criterion

I am working with STS in eclipse Juno ,Spring 3.1.1 ,hibernate 4.1, tomcat 7 and mySQL.
I created a simple MVC template project. my purpose is that the user will enter some data to a form, and that data will
be saved in the database.
I have created:
web layer:
the simple form.
the controller which recieve the data from the form and pass it to the service layer.
service layer:
a service class which contains a DAO field and operate a dao method.
data access layer:
A mock DAO implementation which doesn't commincate with the database.
A Real DAO implementation which doesn commincate with the database.
When i checked the system with the mock DAO implementation, everything was OK - going from the web layer to the mock DAO.
but when injected the real DAO, i just got an 404 error, and nothing in the happened in the Database.
I will show only the DAO implementation and the root-context.xml because this is where i think the problem.
My DAO Implementation:
#Repository
public class Presentation_page_dao_hibernate_Impl implements Presentation_page_dao {
private SessionFactory sessionFactory;
#Autowired
public Presentation_page_dao_hibernate_Impl(SessionFactory sessionFactory) {
this.sessionFactory=sessionFactory;
System.out.println("Hi! i'm in ActionDao_HibernateImpl constructor");
}
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
public void create(Presentation_page pp) {
currentSession().beginTransaction();
currentSession().save(pp);
currentSession().getTransaction().commit();
currentSession().close();
}
public Presentation_page read(int pageid) throws PresentationPageNotFoundException {
currentSession().beginTransaction();
Criteria criteria=currentSession().createCriteria(Presentation_page.class);
criteria.add(Restrictions.eq("page_id", pageid));
List<Presentation_page> list_of_pages=criteria.list();
currentSession().getTransaction().commit();
currentSession().close();
for(Presentation_page pp:list_of_pages) {
if (pp.getPage_id()==pageid){
return pp;
}
}
return null;
}
public void update(Presentation_page pp) throws PresentationPageNotFoundException {
currentSession().beginTransaction();
currentSession().update(pp);
currentSession().getTransaction().commit();
currentSession().close();
}
#Override
public void delete(Presentation_page pp) throws PresentationPageNotFoundException {
currentSession().beginTransaction();
currentSession().delete(pp);
currentSession().getTransaction().commit();
currentSession().close();
}
}
This is my root-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
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">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- For annotations -->
<context:component-scan
base-package="my.topLevel.pack">
</context:component-scan>
<import resource="hibernate2.xml"/>
</beans>
This is my hibernate.xml:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/spring_presentation</property>
<property name="connection.username">rotemya</property>
<property name="connection.password">*******</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="my.topLevel.pack.Domain"/>
</session-factory>
</hibernate-configuration>
I have the following dependencies to the pom.xml:
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>my.topLevel</groupId>
<artifactId>pack</artifactId>
<name>SpringSTS_Sample_Project</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.13</version>
</dependency>
</dependencies>
</project>
This are my hibernate jar files:
I'm getting the following error:
java.lang.NoClassDefFoundError: org/hibernate/criterion/Criterion
Any ideas?
Ok-problem solved!
I removed all the jars from the hibernate library file (which i created), and add them all via Maven (the pom.xml file). and the error was gone..

Categories