简体   繁体   中英

Getting Exception while connecting Spring to hibernate using H2 database

I am getting below exception:

log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mysessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.naveen.java.InsertTest.main(InsertTest.java:12)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:508)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:677)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    ... 12 more
Caused by: org.dom4j.DocumentException: Connection timed out: connect Nested exception: Connection timed out: connect
    at org.dom4j.io.SAXReader.read(SAXReader.java:484)
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:499)
    ... 16 more

Below is employee .java

package com.naveen.java;

import javax.persistence.Id;

public class Employee {

private int id;
private String name;
private int salary;
private String LASTNAME ;

public String getLASTNAME() {
    return LASTNAME;
}
public void setLASTNAME(String lASTNAME) {
    this.LASTNAME = lASTNAME;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public float getSalary() {
    return salary;
}
public void setSalary(int salary) {
    this.salary = salary;
}

}

below is employeedao.java

package com.naveen.java;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
    this.template = template;
}

public void saveEmployee(Employee e){
    template.save(e);
}

public void updateEmployee(Employee e){
    template.update(e);
}

public void deleteEmployee(Employee e){
    template.delete(e);
}
}

below is inserttest.java

package com.naveen.java;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class InsertTest {
public static void main(String[] args) {

    ApplicationContext con=new ClassPathXmlApplicationContext("applicationContext.xml");
    //Resource r=new ClassPathResource("applicationContext.xml");
    EmployeeDao dao=(EmployeeDao)con.getBean("d");

    Employee e=new Employee();
    e.setId(147);
    e.setName("kumar");
    e.setSalary(70000);

    //dao.saveEmployee(e);
    dao.updateEmployee(e);
}
}

below are both the xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  


   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="org.h2.Driver"/>
        <property name="url" value="jdbc:h2:~/test"/>
        <property name="username" value="sa"/>
        <property name="password" value="123"/>
    </bean> 


<bean id="mysessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"></property>  

        <property name="mappingResources">  
         <list>
        <value>employee-hbm.xml</value>  
         </list>
        </property>  

       <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>  
                <prop key="hibernate.show_sql">true</prop>  

            </props>  
        </property>  
    </bean>  

    <bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">  
    <property name="sessionFactory" ref="mysessionFactory"></property>  
    </bean>  

    <bean id="d" class="com.naveen.EmployeeDao">  
    <property name="template" ref="template"></property>  
    </bean>  </beans>

2nd xml mapping

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">


<hibernate-mapping>
   <class name="com.naveen.java.Employee" table="EMP558">

      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="NAME" type="string"/>
      <property name="lastName" column="LASTNAME" type="string"/>
      <property name="salary" column="salary" type="double"/>
   </class>
</hibernate-mapping>

I have tried to link through JDBC and it's working fine.

薪水字段具有int类型,但是在休眠映射中有双精度型

This might be caused because the hibernate trying retrieving the dtd file. so, the workaround could be :

  1. change the value of the dtd from that to "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM