I would like to get a simple integration test with Tomcat and Spring 4 running, injecting a spring component and use my existing data source configuration from Tomcat. I don't want to configure my DataSource twice.
Everything, including my data source, is configured in the file WebContent/WEB-INF/application-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:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:jee="http://www.springframework.org/schema/jee" 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.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
<!-- annotations in bean classes -->
<!-- context:annotation-config / -->
<!-- mvc:annotation-driven / -->
<context:component-scan base-package="com.mycompany.package.**" />
<jpa:repositories base-package="com.mycompany.package.**" />
<!-- <aop:aspectj-autoproxy proxy-target-class="true"/> -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="packagePU" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
</property>
<property name="jpaPropertyMap">
<props>
<prop key="eclipselink.weaving">false</prop>
</props>
</property>
</bean>
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="generateDdl" value="false" />
<property name="showSql" value="true" />
</bean>
<bean id="jpaDialect"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect" />
<!-- <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"/> </bean> -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="i18n/messages" />
</bean>
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/DefaultDB" />
</beans>
I am using this tutorial http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-ctx-management, but I don't fully understand how I can just run my test in the context of Tomcat that provides my DataSource.
Currently, I am this far:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = { "file:WebContent/WEB-INF/application-context.xml"})
public class SimulatorTest {
#Autowired
private ShiftSimulator simulator;
#BeforeClass
public void setup() {
// ???
}
#Test
public void testShiftStart() {
System.out.println("Hello world");
}
}
Currently, I get this error when running the test
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:WebContent/WEB-INF/application-context.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
...
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
...
I fully understand that there needs to be a InitialContext, but how can I provide my test with my context that is provided by Tomcat, including my Data Source configuration? I don't want to set my data source connection credentials twice.
Solved it. Just to recap the problem: Spring tries to create the dataSource bean and fails at looking up the JNDI name - because there is no JNDI available.
So what I did for testing, I just created another XML files that overrides the bean dataSource. I ignored the file in version control and ask every developer to copy this file in place:
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.sap.db.jdbc.Driver"
p:url="jdbc:sap://xxx:30015"
p:username="sa"
p:password="">
</bean>
</beans>
In the test class, I am providing the additional file reference that overrides dataSource so it never tries to do the failing JNDI lookup:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = { "file:WebContent/WEB-INF/application-context.xml", "file:WebContent/WEB-INF/test-datasource.xml" })
public class SimulatorTest {
...
TomcatJNDI offers a comfortable solution for this problem. It's based on Tomcat's JNDI system and initializes only Tomcat's JNDI environment without starting the server. So you can access all your resources as configured in Tomcat's configuration files in tests or from within any Java SE application. Usage is simple, e. g.
TomcatJNDI tomcatJNDI = new TomcatJNDI();
tomcatJNDI.processContextXml(contextXmlFile);
tomcatJNDI.start();
DataSource ds = (DataSource) InitialContext.doLookup("java:comp/env/path/to/datasource");
Find more about it here.
I have builded a java application(maven) to run on server.I use Eclipse Luna, Spring 4 and Hibernate 4.When I run it, I have an error:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF//applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:736)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5016)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5528)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3762)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXmlQueue(Configuration.java:3751)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3739)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:372)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:454)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:439)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
... 21 more
Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mapping com.hibernate.data.Person
at org.hibernate.cfg.Configuration$MappingsImpl.addClass(Configuration.java:2835)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:178)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3759)
... 31 more
Searching similar questions on web,I thought it occurs due to lack of some hibernate dependencies and added them.But it didn't work.Now, I am out of ideas!
My project is here: https://github.com/fsel/Spring-Hibernate-JSF-MySQL-Eclipse-Integration/tree/master/Spring-Hibernate-JSF-MySQL-Example
Any help would be appreciated.
Thanks!
The Person Class is loaded twice.
In Spring configuration - applicationContext.xml file you have :
<property name="mappingResources">
<list>
<value>domain-classes.hbm.xml</value>
</list>
</property>
Also in hibernate configuration - hibernate.cfg.xml file you are loading it once again:
<mapping resource="domain-classes.hbm.xml"/>
To fix the issue, just remove one of the above entries, either from Spring configuration file or Hibernate configuration file.
Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mapping com.hibernate.data.Person
at org.hibernate.cfg.Configuration$MappingsImpl.addClass(Configuration.java:2835)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:178)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3759)
above exception convey that there are duplicate mapping for com.hibernate.data.Person
your hinernate.cfg.xml has below code
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/PERSONDB</property>
<property name="hibernate.connection.username">fulden</property>
<property name="hibernate.connection.password">secret_pass</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Specify session context -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Show SQL -->
<property name="show_sql">true</property>
<!-- Referring Mapping File -->
<mapping resource="domain-classes.hbm.xml"/>
</session-factory>
</hibernate-configuration>
and your applicationContext.xml has below code
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- Enable Spring Annotation Configuration -->
<context:annotation-config />
<!-- Scan for all of Spring components such as Spring Service -->
<context:component-scan base-package="com.spring.service"></context:component-scan>
<!-- Create Data Source bean -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/PERSONDB" />
<property name="username" value="fulden" />
<property name="password" value="secret_pass" />
</bean>
<!-- Define SessionFactory bean -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>domain-classes.hbm.xml</value>
</list>
</property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Detect #Transactional Annotation -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
if you closely observe both files you are duplicating hibernate mapping resource
In hibernate.cfg.xml
<mapping resource="domain-classes.hbm.xml"/>
In a applicatinContext.xml
<property name="mappingResources">
<list>
<value>domain-classes.hbm.xml</value>
</list>
</property>
solution:
removing mappingResources property from applicatinContext.xml file should resolve you problem
thank you
You do not have a constructor without arguments in Person.
Hibernate, and code in general that creates objects via reflection use
Class.newInstance() to create a new instance of your classes. This
method requires a public no-arg constructor to be able to
instantiate the object. For most use cases, providing a no-arg
constructor is not a problem.
Source :
Why does Hibernate require no argument constructor?
Im using WebSphere 8.5.5 Liberty profile to deploy an application that is using a datasource defined and exposed thru jndi. But im unable to use the datasource from my application. My server.xml looks like this:
<server description="new server">
<!-- Enable features -->
<featureManager>
<feature>jsp-2.2</feature>
<feature>jndi-1.0</feature>
<feature>ejbLite-3.1</feature>
<feature>jdbc-4.0</feature>
</featureManager>
<dataSource id="mssqlserver" jndiName="jdbc/sqlserver_prod" type="javax.sql.DataSource">
<jdbcDriver libraryRef="MSJDBCLib"/>
<connectionManager numConnectionsPerThreadLocal="10" id="ConnectionManager" minPoolSize="1"/>
<properties.microsoft.sqlserver username="sa" password="" databaseName="PROD"
serverName="10.211.55.4" portNumber="1433"/>
</dataSource>
<library id="MSJDBCLib">
<fileset dir="/Users/alter/Devel/sqlserver" includes="sqljdbc4.jar"/>
</library>
<httpEndpoint id="defaultHttpEndpoint"
host="0.0.0.0"
httpPort="9080"
httpsPort="9443" />
<application id="ee1" location="/Users/alter/Devel/xxxx/src/ear/target/ee1-ear.ear" name="ear_ear_exploded" type="ear" >
<classloader delegation="parentLast" commonLibraryRef="MSJDBCLib" />
</application>
<application id="ee1-web" location="/Users/alter/Devel/xxxx/src/web/target/ee1-web" name="web_exploded" type="war" />
</server>
Im using this spring configuration file to inject the datasource:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- START CONFIG DS -->
<bean id="dataSourcePROD" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/sqlserver_prod"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSourcePROD"/>
<property name="mapperLocations" value="classpath*:mappers/**/*.xml"/>
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="genericMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" abstract="true">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
<property name="addToConfig" value="true"/>
</bean>
</beans>
Spring is able to found my "datasource" object from JNDI, but it can't cast the delivered object to javax.sql.Datasource.
The actual exception is :
org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.ibm.ws.jdbc.DataSourceService' to required type 'javax.sql.DataSource' for property 'dataSource';
Note1: I have no reference to the jdbc drivers in the deployable artifacts (ear, wars, etc...)
Im missing some configuration parameters in server.xml for the datasource definition??.
you may want to have a look at the Spring helper class WebSphereDataSourceAdapter. IBM has a knack of 'wrapping' services in services which requires a little 'unwrapping' to use.
have a look at this in the Spring API docs as a possible hint on what to try
I have similar code working but I've added the spring jee:jndi-lookup tag for lookup of the datasource inside spring.
<jee:jndi-lookup id="dataSourcePROD" jndi-name="jdbc/sqlserver_prodS" resource-ref="false" expected-type="javax.sql.DataSource"/>
username is wrong attribute in properties.microsoft.sqlserver element. You should use user instead:
<properties.microsoft.sqlserver user="sa" password="" databaseName="PROD"
serverName="10.211.55.4" portNumber="1433"/>
When I am running junit test class the below exception arises? How can i resolve this?
Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
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.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 8
at org.springframework.asm.ClassReader.readUnsignedShort(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.asm.ClassReader.<init>(Unknown Source)
at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:48)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:101)
at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
at org.springframework.context.annotation.ConfigurationClassUtils.checkConfigurationClassCandidate(ConfigurationClassUtils.java:70)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:233)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:203)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:617)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:103)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
at org.springframework.test.context.support.DelegatingSmartContextLoader.loadContext(DelegatingSmartContextLoader.java:228)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124)
my test class is
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations="classpath:dispatcher-servlet.xml")
public class CandidateDAOImplTest{
#Autowired
public CandidateDAO candidateService;
#Test
public void testGetCandidate() {...}
}
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
>
<context:component-scan base-package="com.global" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>database.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="candidateService" class="com.global.dao.impl.CandidateDAOImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<!-- Define a Transaction Manager -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<!-- Turn on support for transaction annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
its located at web/WEB-INF/dispatcher-servlet.xml.
I am using netbeams ied 7.3 and glassfish server 3.0
Most likely you have lambda expression inside one of your spring beans. Apparently, spring 3 beans can't initialize if there is a lambda somewhere in their code. In case migration to spring 4 is not an option, try to rewrite your lambda expressions using anonymous classes, like
Function<A,B> lambda = new Function() {
public B apply(A s) { ... }
}
or move lambda code out of the spring bean. I had the same issue and it helped me, I could still use spring 3 with jre/jdk 8.
Avoids this failure:
Caused by: java.lang.ArrayIndexOutOfBoundsException: 10348
at org.springframework.asm.ClassReader.<init>(Unknown Source)
You have not stated which JDK you are using. If you are using 1.8 then you might find that you will need to upgrade Spring to 4 (or 3.2.9+ as yurez has pointed out).
See the answer to this question:
Java 1.8 ASM ClassReader failed to parse class file - probably due to a new Java class file version that isn't supported yet
The problem is the location of your xml file. WEB-INF is not part of the classpath. Try copying it under the "src" folder.
Try putting the file under src folder. It will be then copied to the WEB-INF/classes folder. Then you can refer to it as classpath:dispatcher-servlet.xml.
If the file is not directly under the classes directory, then you cannot use the location as classpath:dispatcher-servlet.xml in your test
There seems to be some invalid class file on your classpath.
A blog(http://blog.163.com/mxl_880310/blog/static/1847222162012320102631220/) (in Traditional Chinese) describes a similar problem, the author solves it by checking if there is a zero size class file.
having more issues with seting up hibernate with spring3. this time it is saying that connection is nul as the dialect is not set which it is on my hibernate.cfg.xml file.
here is the full exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySessionFactory' defined in URL [file:war/WEB-INF/datasource-config.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:96)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:44)
at org.springframework.test.context.TestContext.buildApplicationContext(TestContext.java:198)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:233)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:126)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:85)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:95)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:139)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:97)
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:67)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:172)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:71)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2270)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2266)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1735)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1775)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:184)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:314)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 29 more
Here is my dataSource-config.xml thats ets up the sessionfactory
<?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:tx="http://www.springframework.org/schema/tx" 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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password} " />
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.jr.freedom"/>
<property name="hibernateProperties" value="classpath:hibernate.cfg.xml"/>
</bean>
<!-- Declare a transaction manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="mySessionFactory" />
</beans>
And below is the hibernate.cfg.xml file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/freedom</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<!-- JDBC connection pool, use Hibernate internal connection pool -->
<property name="connection.pool_size">25</property>
<!-- Defines the SQL dialect used in Hiberante's application -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Display and format all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Mapping to hibernate mapping files -->
<!--mapping resource="org/kodejava/example/hibernate/app/Label.hbm.xml"/-->
</session-factory>
</hibernate-configuration>
As you can see, the dialect is being set.
edit: my database.properties file
# DB properties file
database.url=jdbc:mysql://localhost:3306/freedom
database.driver=com.mysql.jdbc.Driver
database.user=root
database.password=password
database.maxConnections=25
edit: here is a full stack trace. accessing the database could be the issue but i can succefully access it via command prompt?
2288 [main] WARN org.hibernate.engine.jdbc.internal.JdbcServicesImpl - HHH000342: Could not obtain connection to query metadata : Cannot create PoolableConnectionFactory (Access denied for user 'root'#'localhost' (using password: YES))
2289 [main] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#4f549ceb: defining beans [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.config.viewControllerHandlerMapping,userService,myDataSource,mySessionFactory,transactionManager,propertyConfigurer,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,viewResolver,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,hello,userController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
2289 [main] DEBUG org.springframework.beans.factory.support.DisposableBeanAdapter - Invoking destroy method 'close' on bean with name 'myDataSource'
2289 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#14': [org.springframework.web.servlet.config.viewControllerHandlerMapping]
2289 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#8': [org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0]
2289 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#1': [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0]
2290 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)': [org.springframework.web.servlet.handler.MappedInterceptor#0]
The database connection is missing. Add to your hibernate.cfg.xml file a lines like this
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/your_database
</property>
<property name="connection.username">your_user</property>
<property name="connection.password">your_password</property>
(replace localhost if the database is not installed on your computer, and set the values beginning with your_ in my example).
I had this error with JPA, then I just added this line to application.properties:
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
based on this post: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
I had the same problem. Switching from the Apache Commons DataSource:
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password} " />
</bean>
To C3P0:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://ipadress:3306/schema" />
<property name="user" value="root" />
<property name="password" value="abc" />
</bean>
made my problem go away. Maybe someone can explain why, I am just happy it works and wanna share what little I know :)
I think its the problem of not loading your hibernate.cfg.xml file in your application.
I too got the same problem. I have tried with the following code in my project:
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
Then it has worked fine.
Hope this will help.
This issue comes if your mysql-connector version and mysql-installer version is different.
Internally it will throw Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client.
So you need make your mysql-connector version and mysql-installer version same...
I you are using hibernate and InnoDB why don't you set the hibernate.dialect to org.hibernate.dialect.MySQL5 or org.hibernate.dialect.MySQL.
and the connection property to hibernate.connection.url.
i think you are not configure hibernate.cfg.xml.
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory factory = configuration.buildSessionFactory();
I think your datasource-config.xml is not in classpath
instead of having this file in WEB-INF/datasource-config.xml
copy it to WEB-INF/classes/datasource-config.xml
Added the following in persistence.xml file,
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
You did't post your session factory initialization code. But I guess this is the same problem with this one
From Hibernate 4.3.2.Final, StandardServiceRegistryBuilder is introduced. Please follow this order to intialize, e.g.:
Configuration configuration = new Configuration();
configuration.configure("com/jeecourse/config/hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Please double check your code.
I think you don't create the Configuration like below.
Configuration conf = new Configuration().configure();
Best
I think the error cased by unloading hibernate.cfg.xml file after you have created the Configuration Object like this:
Configuration config = new Configuration();
config.configure("hibernate.cfg.xml");
I had the the same problem and the issue was, that my computer was not entered in the pg_hba.conf of the postgres database that allows which Clients(IP-Adresses) are allowed to speak with the database.
btw: Other users tells that the error raises too if they simply forget starting database service locally
Creation of ServiceRegistry instance separately and pass it to buildSessionFactory may cause this error. Try to create SessionFactory instance as follows:
private static SessionFactory factory;
factory = cfg.buildSessionFactory(
new ServiceRegistryBuilder().applySettings(cfg.getProperties())
.buildServiceRegistry());
We were recently facing the same issue with one of our deployment, as we were also using hibernate and dialect is null is a vague error.
I use was with connection string itself and did the changes below to make it work
connectionUrl :- jdbc:mysql://127.0.0.1:3306/{{dbName}}?serverTimezone=UTC&allowPublicKeyRetrieval=true&useSSL=false
Steps how did we solve it
1) We ran simple DB connection with JDBC driver that will gave the exception of time zone.
2) we found the issue with time zone and had to add more properties in connection string as show above.
3) We also added 2 other properties as still it was not working.
Dialect is not set is vague to took lot of our time, I hope this helps.
This worked for me added the dialect property...
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="project_name" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.schema-generation.drop-source" value="script-then-metadata"/>
<property name="dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>
I face this problem when I project update , the error is javax.persistence.jdbc.url', 'hibernate.connection.url', or 'hibernate.dialect'
and I found the solution. it work fine.
here is the details solution