java.lang.NoClassDefFoundError while using HibernateTemplate - java

I was trying to understand the working of HibernateTemplate in Spring-hibernate environment. Since I am new to HibernateTemplate, I feel difficult to understand the errors. In my project I have used all the jar files availabe in spring-framework-4.0.3 and hibernate-4.3.5. Some of the additional jars used in this project are:
*cglib-nodep-2.1.3.jar
*commons-logging.jar
*ojdbc14.jar
*tomcat-dbcp-7.0.30.jar
Following java/xml files were used :
StudentDaoInterface.java
package dao;
import java.util.List;
import model.Student;
public interface StudentDaoInterface {
public int save(Student st);
public boolean update(Student st);
public boolean delete(Student st);
public Student findbyPK(int pk);
public List<Student> findAllUsingHQL();
public List<Student> findAllUsingCriteria();
}
StudentDaoImplHT.java
package dao;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate4.HibernateTemplate;
import model.Student;
public class StudentDaoImplHT implements StudentDaoInterface {
private HibernateTemplate ht;
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
#Override
public int save(Student st) {
int i=(Integer)ht.save(st);
return i;
}
#Override
public boolean update(Student st) {
ht.update(st);
return true;
}
#Override
public boolean delete(Student st) {
ht.delete(st);
return true;
}
#Override
public Student findbyPK(int pk) {
Student st = (Student)ht.get(Student.class,pk);
return st;
}
#Override
public List<Student> findAllUsingHQL() {
List list = ht.find("from student");
return list;
}
#Override
public List<Student> findAllUsingCriteria() {
DetachedCriteria dc = DetachedCriteria.forClass(Student.class);
List list = ht.findByCriteria(dc);
return list;
}
}
Student.java
package model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student",schema="system")
public class Student {
#Id
private int id;
private String name;
private String email;
private String address;
public Student(int id, String name, String email, String address) {
super();
this.id = id;
this.name = name;
this.email = email;
this.address = address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setAddress(String address) {
this.address = address;
}
}
test.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="bds" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="manager"/>
<property name="maxActive" value="15"/>
<property name="maxIdle" value="5"/>
<property name="maxWait" value="5000"/>
</bean>
<bean id="sf" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="bds" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>model.Student</value>
</list>
</property>
</bean>
<bean id="ht" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sf" />
</bean>
<bean id="dao" class="dao.StudentDaoImplHT">
<property name="ht" ref="ht" />
</bean>
</beans>
SaveClient.java
package test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.StudentDaoInterface;
import model.Student;
public class SaveClient {
public static void main(String[] args){
ConfigurableApplicationContext cap = new ClassPathXmlApplicationContext("resources/test.xml");
StudentDaoInterface dao = (StudentDaoInterface)cap.getBean("dao");
Student st = new Student(222,"bbb","bbb#gmail.com","hyd");
dao.save(st);
System.out.println("success");
cap.close();
}
}
After running the code SaveClient.java I face following errors:
Dec 17, 2017 9:27:52 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#3f8f9dd6: startup date [Sun Dec 17 09:27:52 IST 2017]; root of context hierarchy
Dec 17, 2017 9:27:52 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [resources/test.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sf' defined in class path resource [resources/test.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at test.SaveClient.main(SaveClient.java:13)
Caused by: java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.privateGetPublicMethods(Unknown Source)
at java.lang.Class.privateGetPublicMethods(Unknown Source)
at java.lang.Class.getMethods(Unknown Source)
at org.springframework.beans.ExtendedBeanInfoFactory.supports(ExtendedBeanInfoFactory.java:54)
at org.springframework.beans.ExtendedBeanInfoFactory.getBeanInfo(ExtendedBeanInfoFactory.java:46)
at org.springframework.beans.CachedIntrospectionResults.<init>(CachedIntrospectionResults.java:275)
at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:188)
at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:327)
at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptorInternal(BeanWrapperImpl.java:359)
at org.springframework.beans.BeanWrapperImpl.isWritableProperty(BeanWrapperImpl.java:438)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1458)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
... 11 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.engine.FilterDefinition
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)
... 26 more

You should use org.springframework.orm.hibernate4.LocalSessionFactoryBean instead of org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean. But in doc, it says that the following, so be careful about your Spring version or decrease your Hibernate from 4.3.5. to 4.2 or 4.1 as documentation suggests.
This variant of LocalSessionFactoryBean requires Hibernate 4.0 or higher. Note that this version is not compatible with the (the quite refactored) Hibernate 4.3 yet; please upgrade to the Spring 4.0 line for full Hibernate 4.3 support. We recommend using this version with the latest Hibernate 4.1.x or 4.2.x releases.

Related

Spring-Hibernate Integration Framework

I am trying to integrate the spring and hibernate.I want to save my data into database using this functionality. My files are attached as follows.
Employee.java
package springhibernate;
public class Employee {
private int id;
private String name;
private float salary;
public Employee() {
super();
}
public Employee(int id, String name, float salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp558">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
EmployeeDao.java
package springhibernate;
import java.util.ArrayList;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template)
{
this.template = template;
}
//method to save employees
public void saveEmployee(Employee e)
{
template.save(e);
}
//method to update employees
public void updateEmployee(Employee e)
{
template.update(e);
}
//method to delete employees
public void deleteEmployee(Employee e)
{
template.delete(e);
}
//method to return employee of given id
public Employee getById(int id)
{
Employee e = (Employee)template.get(Employee.class, id);
return e;
}
//method to return all employees
public List<Employee> getEmployees()
{
List<Employee> list = new ArrayList<Employee>();
list = template.loadAll(Employee.class);
return list;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns: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.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521/XE"></property>
<property name="username" value="system"></property>
<property name="password" value="manager"></property>
</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="springhibernate.EmployeeDao">
<property name="template" ref="template"></property>
</bean>
</beans>
InsertTest.java
package springhibernate;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
#SuppressWarnings("deprecation")
public class InsertTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource r = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(r);
EmployeeDao dao = (EmployeeDao)factory.getBean("d");
Employee e = new Employee();
e.setId(114);
e.setName("varun");
e.setSalary(5000);
dao.saveEmployee(e);
}
}
now while running the above code i am getting the exceptions as follows. i included/ added all the jar files whatever are needed. i also saw some related questions on the stackoverflow but didn't get the proper hints.
errors
Oct 23, 2017 3:12:45 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'd' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'template' while setting bean property 'template'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'template' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/JDBCException
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1469)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
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 springhibernate.InsertTest.main(InsertTest.java:15)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'template' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/JDBCException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1093)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1038)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
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.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 10 more
Caused by: java.lang.NoClassDefFoundError: org/hibernate/JDBCException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1086)
... 18 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.JDBCException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
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)
... 24 more**
can anyone help me to getting out from this errors/exceptions.
Thanks in advance.
I am not exactly sure whether this solution will work just a small hunch.
Replace :
Resource r = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(r);
EmployeeDao dao = (EmployeeDao)factory.getBean("d");
with :
ApplicationContext r = new ClassPathXMLContext("applicationContext.xml);
Employee dao = r.getBean("d");

java.lang.IllegalArgumentException in java spring using constructor injection

Hello i am using constructor injection in my spring demo app when i run this program i got :
java.lang.IllegalArgumentException exception
Anyone have solution where i am wong and whenever i run same program using setter injection it runs perfectly .
Here is my EmployeeBean.java
package cris;
public class Employee {
private int id;
private String name;
public Employee() { }
public Employee(int id,String name) {
this.id=id;
this.name=name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
void show() {
System.out.println(id+" "+name);
}
}
Here is my Address Bean using setter injection
package cris;
public class Address {
private String city,state,country;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString()
{
return city+" "+state+" "+country;
}
}
Here is my spring.xml ie spring config file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="a1" class="cris.Address">
<property name="city" value="Tikamgarh"></property>
<property name="state" value="Mp"></property>
<property name="country" value="India"></property>
</bean>
<bean id="e" class="cris.Employee">
<constructor-arg type="int" value="12"></constructor-arg>
<constructor-arg type="String" value="anil"></constructor-arg>
</bean>
</beans>
And here is my Application Main Method
package cris;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("cris/spring.xml");
Employee emp = (Employee)context.getBean("e");
emp.show();
}
}
kindly provide me suggestion where i am wrong so i will catch the exception thanks
The Exception:
Apr 03, 2017 4:16:16 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#27f8302d: startup date [Mon Apr 03 16:16:16 IST 2017]; root of context hierarchy
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [cris/spring.xml]
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#17550481: defining beans [a1,e]; root of factory hierarchy
Exception in thread "main" java.lang.IllegalArgumentException
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.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:112)
at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:86)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at cris.Test.main(Test.java:8)
When filling POJO's, (for what I know) Spring calls the no-arg constructor by default. If you decide to write a cTor with parameters yourself, you will not get a default cTor generated and you'll have to add a no-arg cTor for spring yourself.
public Employee() { }
Add type to your constructor-arg
<constructor-arg type="int" value="12" />
and
<constructor-arg type="java.lang.String" value="anil" />
EDIT
or you can use indexes
<constructor-arg index="0" value="12" />
and
<constructor-arg index="1" value="anil" />
Have spring.xml like this:
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="a1" class="cris.Address">
<property name="city" value="Tikamgarh"></property>
<property name="state" value="Mp"></property>
<property name="country" value="India"></property>
</bean>
<bean id="e" class="cris.Employee">
<constructor-arg type="int" value="12"></constructor-arg>
<constructor-arg type="String" value="anil"></constructor-arg>
</bean>
</beans>
EDIT
My example:
spring.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="bean" class="Bean">
<constructor-arg index="0" value="Test"/>
<constructor-arg index="1" value="2"/>
</bean>
</beans>
Bean.java
public class Bean {
private String test1;
private int test2;
public Bean(String test1, int test2) {
this.test1 = test1;
this.test2 = test2;
}
public String getTest1() {
return test1;
}
public void setTest1(String test1) {
this.test1 = test1;
}
public int getTest2() {
return test2;
}
public void setTest2(int test2) {
this.test2 = test2;
}
#Override
public String toString() {
return "Bean{" +
"test1='" + test1 + '\'' +
", test2=" + test2 +
'}';
}
}
Test.java
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
final Bean bean = (Bean) ctx.getBean("bean");
System.out.println(bean.toString());
}
}
prints:
Bean{test1='Test', test2=2}
I had the same issue and can't figure out why until I read each comment in current post and found out...
Using Spring 3.* and Java 11 that is a compatibility issue. When I downloaded the latest version (Spring 5.*) and set to the CLASSPATH. Then everything works.

packagesToScan not working with AnnotationSessionFactoryBean

I am new to spring. I was trying to integrate spring with hibernate but
I am not able to get my entity class Employee using packagesToScan, before this I tried annnotatedClasses as well that too didn't work, I also tried wildcards (com.sfb.**.*) with packagesToScan but no luck yet. FYI I am using javax.persistence.Entity so not an import issue too. Below are my spring.xml file and other along with stacktrace:
Spring.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/sonoo"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="AnnotatedSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.sfb.model.*" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="employeeDao" class ="com.sfb.dao.EmployeeDaoImpl">
<property name="sessionFactory" ref="AnnotatedSessionFactory"/>
</bean>
<bean id="dateFormat" class="java.text.SimpleDateFormat">
<constructor-arg value="yyyy-MM-dd" />
</bean>
<bean id="employee" class="com.sfb.model.Employee">
<property name="ename" value="Javed"/>
<property name="dob">
<bean factory-bean="dateFormat" factory-method="parse">
<constructor-arg value="2010-09-30" />
</bean>
</property>
<property name="address" ref="address"/>
</bean>
<bean id="address" class="com.sfb.model.Address">
<property name="streetno" value="23"/>
<property name="city" value="Bhilai"/>
</bean>
</beans>
TestEmp.java:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class TestEmp {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("spring.xml");
EmployeeDao empDao= (EmployeeDao)context.getBean(EmployeeDao.class);
Employee emp = (Employee)context.getBean(Employee.class);
Address addr = (Address)context.getBean(Address.class);
empDao.save(emp,addr);
}
}
Address.java:
package com.sfb.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Address {
#Id
#GeneratedValue
#Column(name="street_no")
private int streetno;
#Column(name="city")
private String city;
public int getStreetno() {
return streetno;
}
public void setStreetno(int streetno) {
this.streetno = streetno;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Employee.java:
package com.sfb.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity()
#Table(name="emp")
public class Employee {
#Column(name="e_name")
private String ename;
#Id
#GeneratedValue
#Column(name="e_id")
private int eid;
#Column(name="dob")
private Date dob;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
EmployeeDao.java:
package com.sfb.dao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public interface EmployeeDao {
public void save(Employee emp , Address addr);
}
EmployeeDaoImpl.java
package com.sfb.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.sfb.dao.EmployeeDao;
import com.sfb.model.Address;
import com.sfb.model.Employee;
public class EmployeeDaoImpl implements EmployeeDao {
private SessionFactory sessionFactory;
#Override
public void save(Employee emp , Address addr) {
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
emp.setAddress(addr);
session.persist(emp);
tx.commit();
session.close();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Exception StackTrace:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.sfb.model.Employee
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:548)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1338)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:180)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:70)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
at com.sfb.dao.EmployeeDaoImpl.save(EmployeeDaoImpl.java:20)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:19)
Please help me thanks in advance
full StackTrace of NullpointerException:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AnnotatedSessionFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1403)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:545)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.sfb.mainemp.TestEmp.main(TestEmp.java:15)
Caused by: java.lang.NullPointerException
at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:135)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1127)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:296)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1112)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1460)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1400)
... 12 more
Here is an error (Employee.java):
#OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade =
CascadeType.ALL)
private Address address;
mappedBy attribute should only used for inverse size of association, so it is not applicable here.
I guess you are trying to build simple unidirectional association.
It should look something like:
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="ADDRESS_ID") /* this is the name of address id column in 'emp' table*/
private Address address;
Here is almost identical example from book.

Getting Exception while connecting Spring to hibernate using H2 database

I am getting below exception:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mysessionFactory' defined in class path resource [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:1420)
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:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.naveen.java.InsertTest.main(InsertTest.java:12)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:508)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:677)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 12 more
Caused by: org.dom4j.DocumentException: Connection timed out: connect Nested exception: Connection timed out: connect
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:499)
... 16 more
Below is employee .java
package com.naveen.java;
import javax.persistence.Id;
public class Employee {
private int id;
private String name;
private int salary;
private String LASTNAME ;
public String getLASTNAME() {
return LASTNAME;
}
public void setLASTNAME(String lASTNAME) {
this.LASTNAME = lASTNAME;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
below is employeedao.java
package com.naveen.java;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void saveEmployee(Employee e){
template.save(e);
}
public void updateEmployee(Employee e){
template.update(e);
}
public void deleteEmployee(Employee e){
template.delete(e);
}
}
below is inserttest.java
package com.naveen.java;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class InsertTest {
public static void main(String[] args) {
ApplicationContext con=new ClassPathXmlApplicationContext("applicationContext.xml");
//Resource r=new ClassPathResource("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)con.getBean("d");
Employee e=new Employee();
e.setId(147);
e.setName("kumar");
e.setSalary(70000);
//dao.saveEmployee(e);
dao.updateEmployee(e);
}
}
below are both the xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:~/test"/>
<property name="username" value="sa"/>
<property name="password" value="123"/>
</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee-hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="com.naveen.EmployeeDao">
<property name="template" ref="template"></property>
</bean> </beans>
2nd xml mapping
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.naveen.java.Employee" table="EMP558">
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="NAME" type="string"/>
<property name="lastName" column="LASTNAME" type="string"/>
<property name="salary" column="salary" type="double"/>
</class>
</hibernate-mapping>
I have tried to link through JDBC and it's working fine.
salary field has int type, but there is double in the hibernate mapping
This might be caused because the hibernate trying retrieving the dtd file. so, the workaround could be :
change the value of the dtd from that to "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
Create your own function to parse the configuration then passed to the hibernate like this
public static Document parseConfiguration(String resourcePath) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false); <-- the magic is here
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(builder.getClass().getResourceAsStream(resourcePath));
}
I am not getting the error you are getting, though I fixed lot of errors in your entity (properties defined in the mapping file not present in the entity). I have reached the step where it is trying to insert the record, so I am well past the stage where you are getting the error.
By looking into the hibernate source file (org.hibernate.cfg.Configuration.addInputStream(Configuration.java:499)) which is throwing error, hibernate is not able to reach your mapping xml file.
Please double check if the mapping file is at proper location and also readable.
Also make sure you have correct version of hibernate jar in the classpath.

Sprig jdbc queryTimeOutException

I have a simple spring jdbc program but when I run the program I get a queryTimeOut exception.
Here is the complete stackTrace
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/dao/QueryTimeoutException
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.<init>(SQLErrorCodeSQLExceptionTranslator.java:87)
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.<init>(SQLErrorCodeSQLExceptionTranslator.java:103)
at org.springframework.jdbc.support.JdbcAccessor.getExceptionTranslator(JdbcAccessor.java:99)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:407)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:519)
at com.test.spring.EmployeeDao.saveEmployee(EmployeeDao.java:14)
at com.test.spring.Test.main(Test.java:13)
Caused by: java.lang.ClassNotFoundException: org.springframework.dao.QueryTimeoutException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 7 more
Table:
create table employee(emp_name varchar2(30),address varchar2(30),salery number(10),emp_id number(10));
Employee.java:
package com.test.spring;
public class Employee {
private String emp_name;
private String address;
private int salery;
private int emp_id;
public Employee()
{
}
public Employee(String emp_name,int emp_id)
{
this.emp_name=emp_name;
this.emp_id=emp_id;
}
public Employee(String emp_name,String address,int salery,int emp_id)
{
this.emp_name=emp_name;
this.address=address;
this.salery=salery;
this.emp_id=emp_id;
}
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getSalery() {
return salery;
}
public void setSalery(int salery) {
this.salery = salery;
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
}
EmployeeDao.java:
package com.test.spring;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int saveEmployee(Employee e){
//String query="insert into employee (emp_name,address,salery,emp_id)values(?,?,?,?)";//not getting any exception
String query="insert into employee (emp_name,address,salery,emp_id)values("+e.getEmp_name()+","+e.getAddress()+","+e.getSalery()+","+e.getEmp_id()+")";//getting queryTimeOutException
return jdbcTemplate.update(query);
}
}
ApplicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns: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="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="mysql" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.test.spring.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
Test.java:
package com.test.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
int status=dao.saveEmployee(new Employee("Amit","Pingla",35000,102));
System.out.println(status);
}
}
The error points out that you're missing a class from your classpath. It doesn't mean that specific exception would get thrown during that particular invocation; but it simply doesn't find the class for it.
To add the QueryTimeoutException class in your classpath, you need to add a dependency on the spring-tx module.
You can add this dependency
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
If your are using maven or this one
[group: 'org.springframework', name: 'spring-tx', version: '4.1.6.RELEASE'],
if you are using gradle.
JdbcTemplate has queryTimeout property, you can try to configure it to a desired value.

Categories