CannotGetJdbcConnectionException with myBatis +GAE + cloudSQL - maven

I'm new to Google App Engine.
I'm trying to use myBatis to connect to google cloudSQL in my maven GAE.
When I tring to SELECT data from cloudSQL, I'll got Exceptions.
At first, I think there might be a SQL statement problem but I can't find it...
Then, when I changed my SQL statements into 'UPDATE',
exceptions also changed from
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
to
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
So I think there's no error in my SQL statements. My app can read XML file and combine SQL sentences successfully. The problem is that I can't get jdbcConnection... But why?
Could anyone give some suggestion...?
Thanks!
Here are my codes and exceptions:
exceptions
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
### The error may exist in gcloud/myapp/sqlMap/mytestProject.xml
### The error may involve mytestProject.getAllChara
### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:73)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:365)
at com.sun.proxy.$Proxy16.selectList(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:188)
at gcloud.myapp.dao.CharacterDataDao.getAllChara(CharacterDataDao.java:29)
at gcloud.myapp.service.MytestProjectService.getAllCharaTest(MytestProjectService.java:36)
at gcloud.myapp.controller.MytestProjectController.to_index(MytestProjectController.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:42)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:177)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:454)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:461)
at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:276)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:320)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:312)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:458)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
### The error may exist in gcloud/myapp/sqlMap/mytestProject.xml
### The error may involve mytestProject.getAllChara
### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:104)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:95)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:91)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:42)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:355)
... 42 more
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
at org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:80)
at org.mybatis.spring.transaction.SpringManagedTransaction.getConnection(SpringManagedTransaction.java:66)
at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:279)
at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:69)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:56)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:267)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:141)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:105)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:81)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:101)
... 49 more
Caused by: java.sql.SQLException: Internal error.
at com.google.appengine.api.rdbms.RdbmsApiProxyClient$ApiProxyBlockingInterface.makeSyncCall(RdbmsApiProxyClient.java:109)
at com.google.appengine.api.rdbms.RdbmsApiProxyClient$ApiProxyBlockingInterface.openConnection(RdbmsApiProxyClient.java:71)
at com.google.cloud.sql.jdbc.internal.SqlProtoClient.openConnection(SqlProtoClient.java:58)
at com.google.cloud.sql.jdbc.Driver.connect(Driver.java:65)
at com.google.cloud.sql.jdbc.Driver.connect(Driver.java:25)
at com.google.appengine.api.rdbms.AppEngineDriver.connect(AppEngineDriver.java:83)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:187)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:173)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:164)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:149)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:119)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
... 59 more
controller
package gcloud.myapp.controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
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 gcloud.myapp.service.MytestProjectService;
#Controller
public class MytestProjectController {
#Autowired
MytestProjectService mytestProjectService = new MytestProjectService();
#RequestMapping("/")
public String to_index(Model model) throws SQLException, IOException {
List<Map<String, String>> charaList = mytestProjectService.getAllCharaTest();
model.addAttribute("charaList", charaList);
return "index";
}
}
service
package gcloud.myapp.service;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import gcloud.myapp.dao.CharacterDataDao;
#Service("MytestProjectService")
public class MytestProjectService implements IMytestProjectService {
#Autowired
CharacterDataDao characterDataDao = new CharacterDataDao();
#Override
public List<Map<String, String>> getAllCharaTest() throws SQLException, IOException{
List<Map<String, String>> charaList = characterDataDao.getAllChara();
return charaList;
}
}
dao
package gcloud.myapp.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.io.IOException;
public class CharacterDataDao extends SqlSessionDaoSupport implements ICharacterDataDao {
#Override
public List<Map<String, String>> getAllChara() throws SQLException, IOException {
List<Map<String, String>> charaList = getSqlSession().selectList("getAllChara");
return charaList;
}
}
sqlMap(mytestProject.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mytestProject">
<resultMap id="charaListMap" type="java.util.Map">
<result property="id" column="ID" jdbcType="VARCHAR" />
<result property="name" column="CHARANAME_CH" jdbcType="VARCHAR" />
</resultMap>
<select id="getAllChara" resultMap="charaListMap">
<![CDATA[
SELECT ID, CHARANAME_CH
FROM charainfo
]]>
</select>
</mapper>
myBatis config
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="gcloud/myapp/sqlMap/mytestProject.xml" />
</mappers>
</configuration>
spring config
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- basic -->
<context:component-scan base-package="gcloud.myapp" />
<!-- basic -->
<!-- view , the rules defined to resolve the view names -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- basic -->
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" />
</bean>
<!-- sqlSessionFactory -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.google.appengine.api.rdbms.AppEngineDriver" />
<property name="url" value="jdbc:google:rdbms://mytestproject:mytestproject-db/mytestproject" />
<property name="username" value="**my user name**" />
<property name="password" value="**my password**" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/WEB-INF/config/SqlMapConfig.xml" />
</bean>
<bean id="characterDataDao" class="gcloud.myapp.dao.CharacterDataDao">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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"
version="2.5">
<servlet>
<servlet-name>SpringServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- if without "init-param", framework will try to load the application
context from a file named [servlet-name]-servlet.xml in WEB-INF directory. -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/SpringConfig.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
pom
<?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>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<groupId>gcloud.myapp</groupId>
<artifactId>MytestProject</artifactId>
<properties>
<app.id>**my app id**</app.id>
<app.version>1</app.version>
<appengine.version>1.9.44</appengine.version>
<gcloud.plugin.version>1.9.44</gcloud.plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.showDeprecation>true</maven.compiler.showDeprecation>
<archiveClasses>true</archiveClasses>
<org.springframework-version>4.1.6.RELEASE</org.springframework-version>
</properties>
<prerequisites>
<maven>3.3.9</maven>
</prerequisites>
<dependencies>
<!-- Compile/runtime dependencies -->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>${appengine.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test Dependencies -->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-testing</artifactId>
<version>${appengine.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>${appengine.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- com.mysql.jdbc.Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId>
<version>1.0.2</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
<build>
<!-- for hot reload of the web application-->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<archiveClasses>true</archiveClasses>
<webResources>
<!-- in order to interpolate version from pom into appengine-web.xml -->
<resource>
<directory>${basedir}/src/main/webapp/WEB-INF</directory>
<filtering>true</filtering>
<targetPath>WEB-INF</targetPath>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine.version}</version>
<configuration>
<enableJarClasses>false</enableJarClasses>
<version>${app.version}</version>
<!-- Comment in the below snippet to bind to all IPs instead of just localhost -->
<!-- address>0.0.0.0</address>
<port>8080</port -->
<!-- Comment in the below snippet to enable local debugging with a remote debugger
like those included with Eclipse or IntelliJ -->
<!-- jvmFlags>
<jvmFlag>-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n</jvmFlag>
</jvmFlags -->
</configuration>
</plugin>
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>gcloud-maven-plugin</artifactId>
<version>${gcloud.plugin.version}</version>
<configuration>
<set_default>true</set_default>
</configuration>
</plugin>
</plugins>
</build>
</project>
2017/1/18 3:40pm update:
Not cloudSQL authorization problem.
I've tried
Connection conn = DriverManager.getConnection("jdbc:google:mysql://**url**/**databaseName**?user=**userName**&password=**password**");
and connected to database successfully.(can do SQL operations.)

............solved it.
It's just a dataSource URL error.
in my spring-config
<!-- sqlSessionFactory -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.google.appengine.api.rdbms.AppEngineDriver" />
<property name="url" value="jdbc:google:rdbms://mytestproject:mytestproject-db/mytestproject" />
<property name="username" value="**my user name**" />
<property name="password" value="**my password**" />
</bean>
change
<property name="url" value="jdbc:google:rdbms://mytestproject:mytestproject-db/mytestproject" />
to
<property name="url" value="jdbc:google:mysql://mytestproject:us-central1:mytestproject-db/mytestproject" />
and then it works.

Related

Query failed with error code 16550 and error message 'not authorized for query on myCollection

I have a spring boot rest application that interacts with MongoDB but when I invoke the controller method, I give the following exception :
com.mongodb.MongoQueryException: Query failed with error code 16550 and error message 'not authorized for query on 'tenant' on server 172.16.233.128:27017
at com.mongodb.connection.ProtocolHelper.getQueryFailureException(ProtocolHelper.java:131) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.QueryProtocol.execute(QueryProtocol.java:295) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.QueryProtocol.execute(QueryProtocol.java:54) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:168) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:289) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.DefaultServerConnection.query(DefaultServerConnection.java:212) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:525) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:510) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:431) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:404) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation.execute(FindOperation.java:510) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation.execute(FindOperation.java:81) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.Mongo.execute(Mongo.java:836) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.Mongo$2.execute(Mongo.java:823) ~[mongo-java-driver-3.4.2.jar:na] .....
these are classes and configuration
pom.xml is
<?xml version="1.0" encoding="UTF-8"?>
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.concretepage</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-mongodb</name>
<description>Spring Boot Demo Project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
xml configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:annotation-config />
<context:property-placeholder location="classpath*:properties/application.properties"/>
<context:component-scan base-package="com.faracloud.mongodbop.controller" />
<mvc:annotation-driven />
<mongo:mongo id="mongo" host="${catalog.mongodb.host}" port="${catalog.mongodb.port}" />
<mongo:db-factory id="mongoDbFactory" dbname="${catalog.mongodb.database}" mongo-ref="mongo"
username="${catalog.mongodb.user}"
password="${catalog.mongodb.password}"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<mongo:repositories base-package="com.faracloud.mongodbop.repository"
mongo-template-ref="mongoTemplate" />
MongoApp.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ImportResource;
#SpringBootApplication
#ImportResource("classpath:spring/mongodbop-context.xml")
public class MongoApp {
public static void main(String[] args) {
ApplicationContext ctx =SpringApplication.run(MongoApp.class,
args);
}
}
TenantRepository.java
import com.faracloud.mongodbop.model.Tenant;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface TenantRepository extends MongoRepository<Tenant,
String> {
}
and Rest Controller
import com.faracloud.mongodbop.model.Tenant;
import com.faracloud.mongodbop.repository.TenantRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class StatisticController {
#Autowired
TenantRepository repo;
#RequestMapping("/greeting")
public List<Tenant> greeting() {
return repo.findAll() ;
}
}
please give me some advice how to handle this error
My problem was solved using these dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<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>
instead of using mongoTemplate and mongoDbFactory for host,dbnameand credentials, I used following configurations in application.properties
spring.data.mongodb.host=x.x.x.x
spring.data.mongodb.port=27017
spring.data.mongodb.database=xxx
spring.data.mongodb.username=***
spring.data.mongodb.password=***
Thank you reviewers.

Spring Maven JUnit NoClassDefFoundError:org/springframework/context /ApplicationContextException

I have created a spring legacy project using Spring STS and xml configuration file spring-context.xml. I am trying to test my DAO class using JUnit (Run as > Maven test) but I get the following error:
initializationError(net.mozaikdev.samples.dao.test.AddressDAOTest) Time elapsed: 0.006 sec <<< ERROR!
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.test.context.support.DelegatingSmartContextLoader]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContextException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:177)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:123)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:146)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.resolveContextLoader(AbstractTestContextBootstrapper.java:467)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:357)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:303)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:109)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:135)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:151)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:142)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:250)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContextException
at org.springframework.test.context.support.DelegatingSmartContextLoader.<init>(DelegatingSmartContextLoader.java:63)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:165)
... 32 more
Caused by: java.lang.ClassNotFoundException: org.springframework.context.ApplicationContextException
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 38 more
I don't understand why I'm getting this exception since I have declared in my pom.xml the dependency to spring-context:
<?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>net.mozaikdev</groupId>
<artifactId>eshop-sample-spring-legacy</artifactId>
<name>eshop-sample-spring-legacy</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<repositories>
<repository>
<id>repository.spring.release</id>
<name>Spring GA Repository</name>
<url>http://repo.spring.io/release</url>
</repository>
<repository>
<id>repository.spring.milestone</id>
<name>Spring Milestone Repository</name>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
<properties>
<java-version>1.8</java-version>
<org.springframework-version>5.0.0.RC3</org.springframework-version>
<org.hibernate-version>5.2.10.Final</org.hibernate-version>
<org.aspectj-version>1.8.10</org.aspectj-version>
<org.slf4j-version>1.7.25</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>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${org.hibernate-version}</version>
</dependency>
<!-- MariaDB Connector J -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.1.1</version>
</dependency>
<!-- HikariCP connection pool -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
</project>
Here is my JUnit test:
#ContextConfiguration(locations = "classpath:application-context.xml")
#RunWith(SpringJUnit4ClassRunner.class)
public class AddressDAOTest {
#Autowired
private AddressDAO addressDAO;
private static final String STREET_1 = "street_1";
private static final String STREET_2 = "street_2";
private static final Integer ZIP_CODE = new Integer(1234);
private static final String CITY = "city";
private static final String REGION = "region";
private static final String COUNTRY = "country";
private static final Boolean IS_DELIVERY_ADDRESS = new Boolean(false);
#Test
#Transactional
#Rollback(value = true)
public void testPersistAndFindById() {
Address address = new Address();
address.setStreet_1(STREET_1);
address.setStreet_2(STREET_2);
address.setZipCode(ZIP_CODE);
address.setCity(CITY);
address.setRegion(REGION);
address.setCountry(COUNTRY);
address.setIsDeliveryAddress(IS_DELIVERY_ADDRESS);
addressDAO.persist(address);
Long id = address.getId();
address = addressDAO.findById(id);
Assert.assertEquals(STREET_1, address.getStreet_1());
Assert.assertEquals(STREET_2, address.getStreet_2());
Assert.assertEquals(ZIP_CODE, address.getZipCode());
Assert.assertEquals(CITY, address.getCity());
Assert.assertEquals(REGION, address.getRegion());
Assert.assertEquals(COUNTRY, address.getCountry());
Assert.assertEquals(IS_DELIVERY_ADDRESS, address.getIsDeliveryAddress());
}
#Test
#Transactional
#Rollback(value = true)
public void testFindAll() {
Address address1 = new Address();
address1.setStreet_1(STREET_1);
address1.setStreet_2(STREET_2);
address1.setZipCode(ZIP_CODE);
address1.setCity(CITY);
address1.setRegion(REGION);
address1.setCountry(COUNTRY);
address1.setIsDeliveryAddress(IS_DELIVERY_ADDRESS);
Address address2 = new Address();
address2.setStreet_1(STREET_1_UPDATE);
address2.setStreet_2(STREET_2_UPDATE);
address2.setZipCode(ZIP_CODE_UPDATE);
address2.setCity(CITY_UPDATE);
address2.setRegion(REGION_UPDATE);
address2.setCountry(COUNTRY_UPDATE);
address2.setIsDeliveryAddress(IS_DELIVERY_ADDRESS_UPDATE);
addressDAO.persist(address1);
addressDAO.persist(address2);
List<Address> addressesList = addressDAO.findAll();
Assert.assertNotNull(addressesList);
Assert.assertTrue(addressesList.size() >= 2);
Assert.assertTrue(addressesList.contains(address1));
Assert.assertTrue(addressesList.contains(address2));
}
}
And finally the application-context.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:jdbc="http://www.springframework.org/schema/jdbc"
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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Enable annotation configuration -->
<context:annotation-config />
<!-- Scan packages for Spring annotations -->
<context:component-scan base-package="net.mozaikdev.samples.dao" />
<context:component-scan base-package="net.mozaikdev.samples.dao.test" />
<!-- Database connection configuration -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="jdbcUrl" value="${spring.datasource.jdbcUrl}"/>
<property name="driverClassName" value="${spring.datasource.driverClassName}"/>
<property name="username" value="${spring.datasource.username}"/>
<property name="password" value="${spring.datasource.password}"/>
<property name="poolName" value="${spring.datasource.hikari.poolName}"/>
<property name="connectionTimeout" value="${spring.datasource.hikari.connectionTimeout}"/>
<property name="maximumPoolSize" value="${spring.datasource.hikari.maximumPoolSize}"/>
<property name="idleTimeout" value="${spring.datasource.hikari.idleTimeout}"/>
<property name="connectionTestQuery" value="${spring.datasource.hikari.connectionTestQuery}"/>
<property name="maxLifetime" value="${spring.datasource.hikari.maxLifetime}"/>
</bean>
<!-- HikariCP datasource bean -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
<constructor-arg index="0" ref="hikariConfig"/>
</bean>
<!-- Enables annotation-driven transaction management. -->
<tx:annotation-driven/>
<!--
Creates the transaction manager bean that integrates the used JPA provider with the
Spring transaction mechanism.
-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- Specifies the default settings that are compatible with Hibernate. -->
<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<!-- Creates the Hibernate entity manager factory bean -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="packagesToScan" value="net.mozaikdev.samples.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${spring.jpa.properties.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${spring.jpa.properties.hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${spring.jpa.properties.hibernate.format_sql}</prop>
<prop key="hibernate.generate_statistics">${spring.jpa.properties.hibernate.generate_statistics}</prop>
</props>
</property>
</bean>
<!-- Enable support for annotation-driven Spring MVC controllers -->
<!-- <mvc:annotation-driven/> -->
I have cleaned my project using Run as > Maven clean and Project > Clean..., and I updated the project Maven > Update project but nothing works. I am stuck now, if somebody can help me to solve this exception it would be great?
Thanks in advance.
Pay attention on root cause error.
It's clear enough:
Caused by: java.lang.ClassNotFoundException:
org.springframework.context.ApplicationContextException
Put Spring lib in your classpath.
Ok I solved that. When I ran run as > maven install it gave me the following error:
maven error reading C:\Users\569128763\.m2\repository\org\springframework\spring-context\5.0.0.RC3\spring-context-5.0.0.RC3.jar invalid LOC header (bad signature)
So the jar file for spring-context was corrupted, I just deleted the springframework directory from my m2 repository and did Maven > Update project, then launched maven install once again and it worked.

No qualifying bean of type [javax.sql.DataSource] found for dependency [javax.sql.DataSource]

when autowired the datasource ,the project will appear error,when i remove the datasource ,the project works normal. i have add the datasource beans in the spring,i do not know where is wrong
i put my project on git address is:
git#github.com:liwei-green/springMVC.git
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.spring</groupId>
<artifactId>springMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.7.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>springMVC</finalName>
</build>
</project>
the spring
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context- 4.1.xsd">
<!-- 加载配置文件 -->
<!-- 扫描service自动注入为bean -->
<context:component-scan base-package="com.springdemo" />
<context:property-placeholder location="jdbc.properties" />
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${jdbc.driver}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<beans>
the DemoController.java
package com.springdemo.controller;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
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 org.springframework.web.servlet.ModelAndView;
import com.springdemo.entity.User;
import com.springdemo.service.UserService;
#Controller
public class DemoController {
#Autowired
private UserService userService;
/*加上
#Autowired
private DataSource dataSource
编译报错,没有这句编译正常*/
#Autowired
private DataSource dataSource;
#RequestMapping("login.do")
public ModelAndView index(HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
System.out.println(userService);
System.out.println(dataSource);
String userName=request.getParameter("userName");
String userAge=request.getParameter("userAge");
User user= userService.findById(3);
if(userName.equals(user.getName())){
return new ModelAndView("sys/success","user",user);
}else{
return new ModelAndView("sys/faild","user",user);
}
}
}
jdbc.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url=mysql://localhost:3306/maven?useUnicode=true&characterEncoding=UTF-8
jdbc.username = root
jdbc.password = 123456
#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = false
hibernate.hbm2ddl.auto = update
hibernate.cache.use_second_level_cache = true
hibernate.cache.use_query_cache = true
hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path = ehcache.xml
enter image description here
The context config listener is missing in web.xml, so the beans in spring.xml are not init, you can add these to your web.xml,
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
BTW: spring.xml path is not correct in the web.xml, you can change to this.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>

java.lang.NullPointerException exception in my controller file (using Spring Hibernate Maven)

The problem happens when I run this part (#RequestMapping("/SearchStaff")) in my controller file. I can display my search form successfullt (the request mapping below SearchStaff).
The problem doesn't seemed to have anything to do with Hibernate. As I've commented the Hibernate stuff but I'm still getting it.
If I comment out this line
message = staffDAO.searchForStaff(search);
in my controller file, it goes through ok. But I don't see anything wrong with searchForStaff function. It's a very simple function that just returns the string "test" and run system.out.println("test").
Can you please help? thanks
But this is the error that I'm getting:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.NullPointerException
org.flinders.staffdirectory.controllers.SearchController.showSearchResults(SearchController.java:25)
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:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
My spring-servlet xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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">
<context:component-scan base-package="org.flinders.staffdirectory.controllers" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<tx:annotation-driven />
<bean
id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/spring.properties" />
<bean
id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean
id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
p:packagesToScan="org.flinders.staffdirectory"/>
<bean
id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"
p:viewClass="org.springframework.web.servlet.view.tiles2.TilesView" />
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"
p:definitions="/WEB-INF/tiles.xml" />
<bean
id="staffDAO"
class="org.flinders.staffdirectory.dao.StaffDAO"
p:sessionFactory-ref="sessionFactory" />
<!-- <bean
id="staffService"
class="org.flinders.staffdirectory.services.StaffServiceImpl"
p:staffDAO-ref="staffDAO" />-->
</beans>
This is my controller file
package org.flinders.staffdirectory.controllers;
import java.util.List;
//import org.flinders.staffdirectory.models.database.SearchResult;
import org.flinders.staffdirectory.models.misc.Search;
import org.flinders.staffdirectory.dao.StaffDAO;
//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.servlet.ModelAndView;
#Controller
public class SearchController {
//#Autowired
private StaffDAO staffDAO;
private String message;
#RequestMapping("/SearchStaff")
public ModelAndView showSearchResults(#ModelAttribute Search search) {
//List<SearchResult> searchResults =
message = staffDAO.searchForStaff(search);
//System.out.println(search.getSurname());
return new ModelAndView("search/SearchForm", "Search", new Search());
//return new ModelAndView("search/SearchResults", "searchResults", searchResults);
}
#RequestMapping("/SearchForm")
public ModelAndView showSearchForm() {
return new ModelAndView("search/SearchForm", "search", new Search());
}
}
my dao class
package org.flinders.staffdirectory.dao;
import java.util.List;
import org.hibernate.SessionFactory;
//import org.springframework.beans.factory.annotation.Autowired;
import org.flinders.staffdirectory.models.database.SearchResult;
import org.flinders.staffdirectory.models.misc.Search;
public class StaffDAO {
//#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public String searchForStaff(Search search) {
/*String SQL = "select distinct telsumm_id as id, telsumm_parent_id as parentId, telsumm_name_title as title, (case when substr(telsumm_surname, length(telsumm_surname) - 1, 1) = ',' then substr(telsumm_surname, 1, length(telsumm_surname) - 1) else telsumm_surname end) as surname, telsumm_preferred_name as firstname, nvl(telsumm_tele_number, '-') as telephoneNumber, nvl(telsumm_role, '-') as role, telsumm_display_department as department, lower(telsumm_entity_type) as entityType from teldirt.teld_summary where (telsumm_search_surname is not null) and not (nvl(telsumm_tele_directory,'xxx') IN ('N','S','D')) and not (telsumm_tele_number IS NULL AND telsumm_alias IS NULL) and (telsumm_alias_list = 'Y' OR (telsumm_tele_directory IN ('A','B'))) and ((nvl(telsumm_system_id_end,sysdate+1) > SYSDATE and telsumm_entity_type = 'P') or (telsumm_entity_type = 'N')) and (telsumm_search_department NOT like 'SPONSOR%')";
if (search.getSurname().length() > 0) {
SQL += " and (telsumm_search_surname like '" + search.getSurname().toUpperCase() + "%')";
}
if (search.getSurnameLike().length() > 0) {
SQL += " and (telsumm_search_soundex like soundex(('%" + search.getSurnameLike().toUpperCase() + "%'))";
}
if (search.getFirstname().length() > 0) {
SQL += " and (telsumm_search_preferred_name like '" + search.getFirstname().toUpperCase() + "%' or telsumm_search_first_name like '" + search.getFirstname() + "%')";
}
if (search.getTelephoneNumber().length() > 0) {
SQL += " and (telsumm_tele_number like '" + search.getTelephoneNumber() + "%')";
}
if (search.getDepartment().length() > 0) {
SQL += " and (telsumm_search_department like '" + search.getDepartment().toUpperCase() + "%')";
}
if (search.getRole().length() > 0) {
SQL += " and (telsumm_search_role like '" + search.getRole().toUpperCase() + "%')";
}
SQL += " order by surname, firstname";
List<Object[]> list = (List<Object[]>) sessionFactory.getCurrentSession().createQuery(SQL).list();
for(int j=0;j<list.size();j++){
Object [] obj= (Object[])list.get(j);
for(int i=0;i<obj.length;i++)
System.out.println(obj[i]);
}*/
System.out.println("test");
return "test";
}
}
my 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.flinders.staffdirectory</groupId>
<artifactId>directory-maven</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>directory-maven Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<org.springframework.version>3.1.3.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.8.Final</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<finalName>directory-maven</finalName>
</build>
</project>
StaffDAO is null . Any reason why you commented out its autowiring.
Also I see private SessionFactory sessionFactory; Autowired is also commented. Please try removing those comments.
//#Autowired

Could not open JPA EntityManager for transaction in spring

I am building a testing application with JPA Hibernate 4.1.7 and Spring 3.1.3 on top.
I am getting a NPE at jta causing JPA EntityManager to fail, here is the stack trace
DEBUG TestContext - Retrieved ApplicationContext for test class [class cvut.dp.foodtables.service.FoodServiceImplTest] from cache with key [[MergedContextConfiguration#61cc1457 testClass = FoodServiceImplTest, locations = '{classpath:/WEB-INF/context/applicationContext.xml}', classes = '{}', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']].
DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean 'txManager'
DEBUG JpaTransactionManager - Creating new transaction with name [testSome]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
DEBUG SessionImpl - Opened session at timestamp: 13525989368
DEBUG TransactionCoordinatorImpl - Skipping JTA sync registration due to auto join checking
DEBUG AbstractEntityManagerImpl - Looking for a JTA transaction to join
WARN TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener#16f88474] to process 'before' execution of test method [public void cvut.dp.foodtables.service.FoodServiceImplTest.testSome()] for test instance [cvut.dp.foodtables.service.FoodServiceImplTest#3210a146]
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NullPointerException
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:427)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.startTransaction(TransactionalTestExecutionListener.java:514)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.startNewTransaction(TransactionalTestExecutionListener.java:272)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:165)
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:358)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.NullPointerException
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:73)
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:115)
at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149)
at org.hibernate.ejb.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1220)
at org.hibernate.ejb.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:178)
at org.hibernate.ejb.EntityManagerImpl.<init>(EntityManagerImpl.java:89)
at org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:179)
at org.springframework.orm.jpa.JpaTransactionManager.createEntityManagerForTransaction(JpaTransactionManager.java:445)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:366)
... 31 more
DEBUG DirtiesContextTestExecutionListener - After test method: context [[TestContext#5579d6f9 testClass = FoodServiceImplTest, testInstance = cvut.dp.foodtables.service.FoodServiceImplTest#3210a146, testMethod = testSome#FoodServiceImplTest, testException = org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NullPointerException, mergedContextConfiguration = [MergedContextConfiguration#61cc1457 testClass = FoodServiceImplTest, locations = '{classpath:/WEB-INF/context/applicationContext.xml}', classes = '{}', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]], class dirties context [false], class mode [null], method dirties context [false].
DEBUG DirtiesContextTestExecutionListener - After test class: context [[TestContext#5579d6f9 testClass = FoodServiceImplTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration#61cc1457 testClass = FoodServiceImplTest, locations = '{classpath:/WEB-INF/context/applicationContext.xml}', classes = '{}', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]], dirtiesContext [false].
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 11.134 sec <<< FAILURE!
I have googled the error to death and still can't find any solution.
Here is the test:
package cvut.dp.foodtables.service;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class FoodServiceImplTest extends BaseServiceTest
{
#Autowired
private FoodService foodService;
public FoodServiceImplTest()
{
super();
}
#Test
public void testSome()
{
Long id = foodService.addFood("test", 15, "test");
assertEquals(1, foodService.getAllFood().size());
}
}
Which extends
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {
"classpath:/WEB-INF/context/applicationContext.xml"})
#TransactionConfiguration(defaultRollback=true, transactionManager="txManager")
#Transactional //extend the transactions to whole tests in order to rollback the tests
public class BaseServiceTest
{
public BaseServiceTest()
{
}
}
I presume the error to be somewhere in my configuration, so I won't post all of the sources here...
Here is my applicationContext.xml (edit: changed to 3.1.xds files, no change)
<!--<?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:webflow="http://www.springframework.org/schema/webflow-config"
xmlns:faces="http://www.springframework.org/schema/faces"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/webflow-config
http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd
http://www.springframework.org/schema/faces
http://www.springframework.org/schema/faces/spring-faces-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
default-autowire="byType"
>
<!-- Enable annotions -->
<context:annotation-config />
<context:component-scan base-package="cvut.dp.foodtables"/>
<!-- #Configurable -->
<context:spring-configured/>
<!-- Property files -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/properties/jdbc.properties</value>
<value>/WEB-INF/properties/jpa.properties</value>
</list>
</property>
</bean>
<!-- JDBC data source -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialSize" value="2" />
<property name="minIdle" value="2" />
</bean>
<!-- JPA settings -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="${jpa.platform}"/>
<property name="generateDdl" value="true"/>
<property name="showSql" value="true"/>
</bean>
</property>
<property name="packagesToScan" value="cvut.dp.foodtables" />
</bean>
<!-- Define transaction manager -->
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- #Transactional support-->
<tx:annotation-driven transaction-manager="txManager" />
</beans>
I don't have persistence.xml
jdbc.properties:
jdbc.driverClassName=org.hibernate.dialect.MySQLDialect
jdbc.url=jdbc:mysql://localhost:3306/FoodTables
jdbc.username=root
jpa.properties:
jpa.platform=org.hibernate.dialect.MySQLDialect
Here is web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- SPRING -->
<context-param>
<description>Spring config files</description>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/context/*.xml
</param-value>
</context-param>
<listener>
<description>Loads Spring on server start</description>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<description>Request -> thread association</description>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<!-- SPRING END -->
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
And my 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>cvut.dp</groupId>
<artifactId>FoodTables</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>FoodTables</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-documentation</artifactId>
<version>3.6.0.Beta2</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.8.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<groupId>org.hibernate.javax.persistence</groupId>
<type>jar</type>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
</dependencies>
<build>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
<testResource>
<directory>src/main/webapp</directory>
<filtering>true</filtering>
<includes>
<include>**/context/applicationContext*.xml</include>
<include>**/properties/*.properties</include>
</includes>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>6.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
The most googled up answer was that I should be setting hibernate.transaction.jta.platform property in persistance.xml, which I don't have. This is my first ever Java EE app and I really don't exactly know what I am doing yet. But this error is frustrating.
I had the same problem. The solution is to use default-autowire="byName" instead of "byType" in your xml configuration. If you have "byType" Spring automatically autowire also the property "jtaDataSource" in the LocalContainerEntityManagerFactoryBean with your definied datasource bean.
While jens answer is correct and solves your problem, i just wanted to add that you don't have to change the default-autowiring for this. You can also set that on every bean itself.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
autowire="byName">
...
Now you still have byType-autowiring on all of your beans except "entityManagerFactory"
This is no password entry defined in your jdbc.projects.
<property name="password" value="${jdbc.password}"/>
It is better to create a standalone user/password for your projects, do not use root in your production.
Try adding a "META-INF/persistence.xml":
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="myUnit" transaction-type="RESOURCE_LOCAL">
</persistence-unit>
</persistence>
Putting a breakpoint at org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo line 91 (PersistenceUnitTransactionType getTransactionType()) might also help you determine why spring thinks you have a jta-datasource or transaction type.

Resources