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.
Related
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");
I am a newbie in Spring + Hibernate, but I have worked on this problem for last one day. I still can not figure out what is the root cause, and what should I do. So, thank you in advance if any one can give me some advice.
Here is a problem, I just write a simple test class, but when I ran, there is an exception:
??: Exception encountered during context initialization - cancelling refresh >attempt: 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.InvalidMappingException: Unable to read XML
Exception in thread "main" >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.InvalidMappingException: Unable to read XML
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.xw.test.Test.main(Test.java:30)
And here is the class source code:
package com.domain;
import java.util.Date;
public class Employee {
private Integer id;
private String name;
private String email;
private java.util.Date hiredate;
private Float salary;
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public java.util.Date getHiredate() {
return hiredate;
}
public void setHiredate(java.util.Date hiredate) {
this.hiredate = hiredate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Employee( String name, String email, Date hiredate,
Float salary) {
this.name = name;
this.email = email;
this.hiredate = hiredate;
this.salary = salary;
}
public Employee(){
}
}
And here is the Employee.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-mapping package="com.domain">
<class name="Employee" table="employee">
<id name="id" type="java.lang.Integer">
<generator class="native" ></generator>
</id>
<property name="email" type="java.lang.String" >
<column name="email" length="64"/>
</property>
<property name="hiredate" type="java.util.Date">
<column name="hiredate" />
</property>
<property name="name" type="java.lang.String">
<column name="name"/>
</property>
<property name="salary" type="java.lang.Float">
<column name="salary"/>
</property>
</class>
</hibernate-mapping>
And here is the ApplicationContext.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<bean id="testService" class="com.xw.test.TestService">
<property name="name" value="XingWang"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#127.0.0.1:1521:orcl"/>
<property name="username" value="scott"/>
<property name="password" value="111111"/>
<property name="initialSize" value="3"/>
<property name="maxActive" value="500"/>
<property name="maxIdle" value="2"/>
<property name="minIdle" value="1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/domain/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.OracleDialect
</value>
</property>
</bean>
</beans>
And the pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>myssh</groupId>
<artifactId>myssh</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebRoot</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.2.Final</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
</dependencies>
And here is the smiple test class source code:
/**
*
*/
package com.xw.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.domain.Employee;
/**
* #author Administrator
*
*/
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");
SessionFactory sf = (SessionFactory) ac.getBean("sessionFactory");
Session s = sf.openSession();
Employee employee = new Employee( "aa", "aa.sohu#com", new java.util.Date(),
(float) 234.56) ;
Transaction tx = s.beginTransaction();
s.save(employee);
tx.commit();
}
}
Thank you so much for any advice!
The properties should be declared like below inside your sessionFactory Bean.
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
</props>
so your sessionFactory bean would be like below.
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/domain/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
</props>
</property>
sometimes there is a chance of cant pick ur config files because of compiler dont konw which file shoul it take for configuration.so for this reason u should explicitly import those config file via 2 methods as i know
1)by using class
#Configuration
#ImportResource(value = {"classpath:{filename-within-resource}/Employee.hbm.xml"},"classpath:{filename-within-resource}/ApplicationContext.cfg.xml")
public class CommonSolutionConfig {
}
2)by using xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<import resource="classpath:{filename-within-resource}/Employee.hbm.xml"/>
<import resource="classpath:{filename-within-resource}/ApplicationContext.cfg.xml"/>
</beans>
hopefully it will solve ur problem
[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
The exception is about table not mapping to class, however I failed to debug what went wrong.
I have checked the xml configurations. the class is UserType and the database table is called UserType as well.
UserType.java:
package com.howtodoinjava.entity;
public class UserType {
private int _userTypeID;
private String _userTypeName;
private boolean _typeIsSuperUser;
public int getUserTypeID() { return _userTypeID; }
public String getUserTypeName() {return _userTypeName; }
public boolean getTypeIsSuperUser() {return _typeIsSuperUser; }
public UserType setUserTypeID(int id) { _userTypeID = id; return this; }
public UserType setUserTypeName(String name) { _userTypeName = name; return this; }
public UserType setTypeIsSuperUser(boolean isSuperUser) { _typeIsSuperUser = isSuperUser; return this; }
}
UserTypeDAOImpl.java:
package com.howtodoinjava.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.howtodoinjava.entity.UserType;
#Repository
public class UserTypeDAOImpl implements UserTypeDAO {
#Autowired
private SessionFactory sessionFactory;
public void add(UserType ut) {
this.sessionFactory.getCurrentSession().save(ut);
}
#SuppressWarnings("unchecked")
public List<UserType> getAll() {
return this.sessionFactory.getCurrentSession().createQuery("from UserType").list();
}
public void delete(Integer id) {
UserType ut= (UserType) sessionFactory.getCurrentSession().load(
UserType.class, id);
if (null != ut) {
this.sessionFactory.getCurrentSession().delete(ut);
}
}
}
EditUserTypeController.java:
#Controller
public class EditUserTypeController{
#Autowired
private UserTypeManager userTypeManager;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String list(ModelMap map)
{
map.addAttribute("UserType", new UserType());
map.addAttribute("UserTypeList", userTypeManager.getAll());
return "editEUserTypeList";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUserType(#ModelAttribute(value="ut") UserType ut, BindingResult result)
{
userTypeManager.add(ut);
return "redirect:/";
}
#RequestMapping("/delete/{id}")
public String deleteUserType(#PathVariable("id") Integer id)
{
userTypeManager.delete(id);
return "redirect:/";
}
public void setUserTypeManager(UserTypeManager new_utm) {
this.userTypeManager = new_utm;
}
}
my UserType-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<context:annotation-config />
<context:component-scan base-package="com.howtodoinjava.controller" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="UserTypeDAO" class="com.howtodoinjava.dao.UserTypeDAOImpl"></bean>
<bean id="UserTypeManager" class="com.howtodoinjava.service.UserTypeManagerImpl"> </bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping resource="UserType.hbm.xml" />
</session-factory>
</hibernate-configuration>
UserType.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.howtodoinjava.entity.UserType" table="UserType">
<meta attribute="class-description">
user type
</meta>
<id name="_userTypeID" column="UserTypeId" type="int"> <generator class="native"/> </id>
<property name="_userTypeName" column="UserTypeName" type="string"/>
<property name="_typeIsSuperUser" column="TypeIsSuperUser" type="string"/>
</class>
</hibernate-mapping>
I appreciate any helps!
The problem is in hibernate mapping configuration:
name: should be same as class field name and
column: is the name of database table column, or the column name to be set while table creation by hibernate.
Note: The mapping file instructs Hibernate how to map the defined class to the database table.
your UserType.hbm.xml should be look like:
<hibernate-mapping>
<class name="com.howtodoinjava.entity.UserType" table="UserType">
<meta attribute="class-description">
user type
</meta>
<id name="_userTypeID" column="userTypeID" type="int">
<generator class="native"/>
</id>
<property name="_userTypeName" column="userTypeName" type="string"/>
<property name="_typeIsSuperUser" column="typeIsSuperUser" type="string"/>
</class>
</hibernate-mapping>
It turned out this is related to the HQL issue: instead of using from UserType, use from com.howtodojava.entity.UserType;
and the error message will be gone.
I'm using myeclipse IDE
After executing my code i'm getting the below Exception
log4j:WARN No appenders could be found for logger
(org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Unknown entity:info.inetsolv.Emp
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister
(SessionFactoryImpl.java:628)
at org.hibernate.impl.SessionImpl.getEntityPersister
(SessionImpl.java:1366)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState
(AbstractSaveEventListener.java:535)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist
(DefaultPersistEventListener.java:93)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist
(DefaultPersistEventListener.java:61)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:646)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:620)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:624)
at info.inetsolv.InsertEmprecord.main(InsertEmprecord.java:22)
POJO CLASS
package info.inetsolv;
#SuppressWarnings("serial")
public class Emp implements java.io.Serializable {
// Fields
private Integer eno;
private String name;
private Double salary;
// Constructors
/** default constructor */
public Emp() {
}
/** minimal constructor */
public Emp(Integer eno) {
this.eno = eno;
}
/** full constructor */
public Emp(Integer eno, String name, Double salary) {
this.eno = eno;
this.name = name;
this.salary = salary;
}
// Property accessors
public Integer getEno() {
return this.eno;
}
public void setEno(Integer eno) {
this.eno = eno;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return this.salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
HibernateSessionFactory.java
package info.inetsolv;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new
ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {
return configuration;
}
}
client program to insert record into DB
InsertEmprecord.java
package info.inetsolv;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class InsertEmprecord {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session hsession = sf.openSession();
Transaction tx = hsession.beginTransaction();
Emp e = new Emp();
e.setEno(6);
e.setName("six");
e.setSalary(1234d);
hsession.persist(e);
tx.commit();
hsession.close();
sf.close();
}
}
And below is my hibernate mapping file
Emp.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="info.inetsolv.Emp" table="EMP" schema="HIB">
<id name="eno" type="java.lang.Integer">
<column name="ENO" precision="5" scale="0" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="10" />
</property>
<property name="salary" type="java.lang.Double">
<column name="SALARY" precision="10" />
</property>
</class>
</hibernate-mapping>
AND below is my hibernate configuration file
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.url">
jdbc:oracle:thin:#localhost:1521:xe
</property>
<property name="connection.username">hib</property>
<property name="connection.password">abc</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="myeclipse.connection.profile">
my oracle drive
</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
You didn't configure mapping for the object Emp. The configuration file hibernate.cfg.xml should contain the mapping to the resource Emp.hbm.xml.
<mapping resource="info/inetsolv/Emp.hbm.xml"/>
I had similar problem for a simple Console application trying to use Hibernate. The solution I arrived to make the add the "packagesToScan" property explicitly for LocalSessionFactoryBean.
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.mg.learning.spring.orm"/> <--- this SOLVED!
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
#Sandhu Santakumar , answer is absolutely right.
Just adding the reason behind this.
By default the JBoss hibernate reverse engineering tool maps class inside the mapping tab but resource attribute is the required attribute that hibernate.cfg.xml should have.
class attribute is optional.
e.g. if your mapping is like this
resource is mandatory attribute and class is optional attribute.
Hope this additional information helps.