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");
Related
In hibernate 5.4 version with Spring Boot 2.2.7. I am getting below exception.
Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of <Project path>.models.Book.isbn
at org.hibernate.property.access.spi.GetterMethodImpl.get(GetterMethodImpl.java:65)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:223)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:5119)
at org.hibernate.id.Assigned.generate(Assigned.java:31)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:115)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:626)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:619)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:614)
at com.vikas.projects.organicecommerce.jpahibernate.QueryExcecutableFile.test(QueryExcecutableFile.java:29)
at com.vikas.projects.organicecommerce.jpahibernate.OrganicEcommerceJpaHibernateApplication.main(OrganicEcommerceJpaHibernateApplication.java:21)
... 5 more
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.access.spi.GetterMethodImpl.get(GetterMethodImpl.java:42)
I have checked other related link, but Im not able to link those with my use case.
I'm using below configuration and models to persist the Book object.
Book.java
package com.vikas.projects.organicecommerce.jpahibernate.models;
import java.math.BigDecimal;
import java.sql.Date;
import lombok.EqualsAndHashCode;
#EqualsAndHashCode
public class Book {
private String isbn;
private String name;
private Date publishdate;
private BigDecimal price;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getPublishdate() {
return publishdate;
}
public void setPublishdate(Date publishdate) {
this.publishdate = publishdate;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
book.hbm.xml
<hibernate-mapping>
<class name="...Book"
table="BOOK" lazy="false">
<id name="isbn">
<column name="ISBN" sql-type="varchar(13)" not-null="true" />
</id>
<property name="name">
<column name="NAME" sql-type="varchar(64)" not-null="true"
unique="true" />
</property>
<property name="publishdate">
<column name="PUBLISHDATE" sql-type="date" />
</property>
<property name="price">
<column name="PRICE" sql-type="decimal" precision="8"
scale="2" />
</property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class"></property>
<property name="connection.url"></property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<property name="hibernate.dialect"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping
resource=".../Book.hbm.xml" />
</session-factory>
</hibernate-configuration>
Method to persist this object
public void test() {
Book book = new Book();
book.setIsbn("1232424");
book.setName("BookName");
book.setPrice(new BigDecimal(23.00));
book.setPublishdate(Date.valueOf("2014-04-04"));
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(book);
tx.commit();
session.close();
}
I'm using microsoft sql server. Please let me know if more details required.
Adding more details. From main function, I'm calling test(), via QueryExecutableFile's instance.
#SpringBootApplication
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class OrganicEcommerceJpaHibernateApplication {
public static void main(String[] args) {
SpringApplication.run(OrganicEcommerceJpaHibernateApplication.class, args);
QueryExcecutableFile queryExcecutableFile = new QueryExcecutableFile(getSessionFactory());
queryExcecutableFile.test();
}
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
}
public class QueryExcecutableFile {
SessionFactory sessionFactory;
public QueryExcecutableFile(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void test() {
Book book = new Book();
book.setIsbn("1232424");
book.setName("BookName");
book.setPrice(new BigDecimal(23.00));
book.setPublishdate(Date.valueOf("2014-04-04"));
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(book);
tx.commit();
session.close();
}
}
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.
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.
[enter image description here][1]
Account.java
package com.hibernateWithSpring;
public class Account {
private int accountNumber;
private String owner;
private double balance;
public Account(){
}
public Account(int accountNumber, String owner, double balance) {
this.accountNumber=accountNumber;
this.owner= owner;
this.balance=balance;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
AccountClient.java
package com.hibernateWithSpring;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class AccountClient {
public static void main(String[] args){
ApplicationContext context=new FileSystemXmlApplicationContext("bin/beans.xml");
AccountDao accountdao = context.getBean("accountDaoBean",AccountDao.class);
accountdao.createAccount(110, "varun",1000);
accountdao.createAccount(111, "vicky",1200);
System.out.println("account created");
accountdao.updateBalance(111,2222);
System.out.println("account updated");
accountdao.deleteAccount(111);
System.out.println("account deleted");
List<Account> account= accountdao.getAllAccount();
for(int i=0;i<account.size();i++){
Account acc=account.get(i);
System.out.println(acc.getAccountNumber()+":"+acc.getOwner()+":"+acc.getBalance());
}
}
}
AccountDao.java
package com.hibernateWithSpring;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class AccountDao extends HibernateDaoSupport
{
public void createAccount(int accountNumbeer, String owner, double balane){
Account account= new Account(accountNumbeer,owner,balane);
getHibernateTemplate().save(account);
}
public void updateBalance(int accountNumber, double newBalance){
Account account= getHibernateTemplate().get(Account.class, accountNumber);
if(account !=null){
account.setBalance(newBalance);
}
getHibernateTemplate().update(account);
}
public void deleteAccount(int accountNumber){
Account account=getHibernateTemplate().get(Account.class, accountNumber);
if(account!=null){
getHibernateTemplate().delete(account);
}
}
#SuppressWarnings("unchecked")
public List<Account> getAllAccount()
{
return getHibernateTemplate().find("from Account");
}
}
Account.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.hibernateWithSpring.Account" table="account">
<id name="accountNumber" column="account_number" type="int"></id>
<property name="owner" column="owner" type="string"></property>
<property name="balance" column="balance" type="double"></property>
</class>
</hibernate-mapping>
beans.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="accountDaoBean" class="com.hibernateWithSpring.AccountDao">
<property name="hibernateTemplate" ref="hibernateTemplateBean"></property>
</bean>
<bean id="hibernateTemplateBean" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sfBean"></property>
</bean>
<bean id="sfBean" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceBean"></property>
<property name="mappingResources">
<value>com/hibernateWithSpring/Account.hbm.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/accountdb"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
My db Details are correct But I have no idea why i am getting this error:-
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountDaoBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Cannot resolve reference to bean 'hibernateTemplateBean' while setting bean property 'hibernateTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplateBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Cannot resolve reference to bean 'sfBean' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sfBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
Things you need to fix:
1 - put the JAR (javaee-api) in your LIB folder
http://mvnrepository.com/artifact/javax/javaee-api/7.0
2 - if you are using Maven, add the following dependency
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
3 - Configure your artifact and include this jar, allowing to be deployed
4 - Put the javaee-api jar in your tomcat/jboss lib folder
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.