no such bean definition exception in spring - java

I am new to the concepts of Spring and Hibernate.
I am using collections in my simple spring program. My idea is to store an author name, address and id into collection. It's a simple spring framework but I am struck with one error.
spring-model.xml
<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-2.5.xsd">
<bean id="book" class="com.vishal.Book">
<property name="author ">
<list>
<ref bean="book1 " />
<ref bean="book2 " />
<ref bean="book3 " />
</list>
</property>
</bean>
<bean id="book1" class="com.vishal.Book">
<property name="name" value="mark twain" />
<property name="address" value="London" />
<property name="id" value="230" />
</bean>
<bean id="book2" class="com.vishal.Book">
<property name="name" value="gutav friedman" />
<property name="address" value="Germany" />
<property name="id" value="231" />
</bean>
<bean id="book3" class="com.vishal.Book">
<property name="name" value=" Erastothe " />
<property name="address" value="spain" />
<property name="id" value="232" />
</bean>
</beans>
main class
package com.vishal;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Springmain {
#SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"spring-model.xml");
Book book = (Book) context.getBean("book");
book.authorName();
}
}
book.java
package com.vishal;
import java.util.List;
public class Book {
private List<Author> author;
public List<Author> getAuthor() {
return author;
}
public void setAuthor(List<Author> author) {
this.author = author;
}
public void authorName() {
for (Author authors : author)
System.out.println(authors.getAddress() + authors.getId()
+ authors.getName());
}
}
author class
package com.vishal;
public class Author {
private String name;
private String address;
private int id;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
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;
}
}
Following is the error which I a getting
Jun 10, 2013 11:29:36 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#161d36b: startup date [Mon Jun 10 11:29:36 IST 2013]; root of context hierarchy
Jun 10, 2013 11:29:36 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-model.xml]
Jun 10, 2013 11:29:37 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1b5998f: defining beans [book,book1,book2,book3]; root of factory hierarchy
Jun 10, 2013 11:29:37 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1b5998f: defining beans [book,book1,book2,book3]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'book' defined in class path resource [spring-model.xml]: Cannot resolve reference to bean 'book1 ' while setting bean property 'author ' with key [0]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'book1 ' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1134)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
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:626)
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 com.vishal.Springmain.main(Springmain.java:10)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'book1 ' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:568)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1102)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:278)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 17 more

There is space in bean references:
whereas actual bean name has no space:
Also as Luiggi suggested Bean definition needs to corrected.
Please check this.

In your Book class you have a List<Author> but in your spring-model.xml file you refer to book1, book2 and book3 as instances of Book, not from Author probably due for copy/paste process and forgetting the most important step: adapt what you pasted.
Just to show an example:
<bean id="book1" class="com.vishal.Book">
It should be
<bean id="book1" class="com.vishal.Author">
Also, you're referring to other beans using
<ref bean="book1 " />
There's a white space in the end that should be trimmed. It should be
<ref bean="book1" />
Similar for other bookX references in your spring-model.xml file.

Related

Hibernate Bean Creating Exception

I am using Spring-ORM to add a Employee* object in Table called emp using HibernateTemplate.
But when I'm trying to execute the program I'm getting this error:
Error creating bean with name 'testBean': Unsatisfied dependency expressed through field 'dao'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:E rror creating bean with name 'empDaoImpl': Unsatisfied dependency expressed through field 'ht'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ht' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is
org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [alter table emp add empno number(10,0) not null]
This is My java bean
#Service
public class TestBean
{
#Autowired
private EmpDao dao;
public void persistEmp(int empid,String empName,int sal,int deptno)
{
Employee e=new Employee();
e.setEmpid(empid);
e.setEmpName(empName);
e.setEmpSalary(sal);
e.setDeptNum(deptno);
dao.save(e);
}
public void updateEmp(int empid,String empName,int sal,int deptno)
{
Employee e=new Employee();
e.setEmpid(empid);
e.setEmpName(empName);
e.setEmpSalary(sal);
e.setDeptNum(deptno);
dao.update(e);
}
public void deleteEmp(int empid)
{
dao.deleteEmployee(empid);
}
public void selectEmps()
{
List lt=dao.selectEmployees();
Iterator it=lt.iterator();
while(it.hasNext())
{
Employee e1=(Employee)it.next();
System.out.println(e1);
}
}
}
*This is my Entity class
#Entity
#Table(name="emp")
public class Employee
{
#Id
#Column(name="empno")
private int empid;
#Column(name="ename")
private String empName;
#Column(name="sal")
private int empSalary;
#Column(name="deptno")
private int deptNum;
//Setters and Getters
public String toString()
{
return "Employee["+empid+" "+empName+" "+empSalary+" "+deptNum+"]";
}
}
This is my EmpDaoImpl class
#Repository
#Transactional
public class EmpDaoImpl implements EmpDao
{
#Autowired
private HibernateTemplate ht;
public void deleteEmployee(int empid)
{
Employee e=(Employee)ht.get(Employee.class, empid);
ht.delete(e);
System.out.println("one Employee object is deleted");
}
public List selectEmployees()
{
List empList=ht.find("from Employee e");
return empList;
}
public void save(Employee e)
{
ht.save(e);
System.out.println("Object is saved ");
}
public void update(Employee e)
{
ht.update(e);
System.out.println("Object is Updated");
}
}
This is my Main class
public class Main
{
public static void main(String[] args)
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
TestBean testB=(TestBean)ctx.getBean("testBean");
testB.persistEmp(7999, "naveen", 55555, 40);
System.out.println("===============================");
}
}
This is my applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.pack1"></context:component-scan>
<bean id="ht" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="ds"></property>
<property name="annotatedClasses">
<list>
<value>com.pack1.entity.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
</value>
</property>
</bean>
<bean id="txm" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<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="tiger"/>
</bean>
<tx:annotation-driven transaction-manager="txm"/>
</beans>
When hibernate.hbm2ddl.auto is set to update Hibernate won't modify existing table column definitions. So, you can manually alter the column definition or drop the table/column and run your code. In the latter case, hibernate will create the column if it is not present.
Please refer here, here and here for more info on hibernate.hbm2ddl.auto options and how they work.

java.lang.NoClassDefFoundError while using HibernateTemplate

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.

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.

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.

Categories