简体   繁体   中英

Java Spring + Hibernate LocalSessionFactoryBean not working

I'm trying to integrate hibernate with spring. Here are my codes:

Main.java

import java.util.List;
import local.bb.entities.Words;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String args[]) {

        ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");
        SessionFactory sf = (SessionFactory)appContext.getBean("sessionFactory");
        Session s = sf.openSession();

        try {

            List<Words> words = s.createCriteria(Words.class).list();
            int i=1;
            for( Words w : words ) {
                System.out.println( "["+ (i++) +"]" + w.getWord());
            }

        } catch(Exception e) {
            e.printStackTrace();
        }

        sf.close();

    }

}

spring.xml

    <?xml version='1.0' encoding='UTF-8' ?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        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.0.xsd
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="local.bb.config">
    </context:component-scan>

    <aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>

Config.java(local.bb.config package)

import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;

@Configuration
public class Config {

    @Bean
    DriverManagerDataSource dataSource() {
        DriverManagerDataSource dmds = new DriverManagerDataSource("jdbc:mysql://localhost:3306/java?zeroDateTimeBehavior=convertToNull");
        dmds.setUsername("root");
        return dmds;
    }

    @Bean
    LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean asfb = new LocalSessionFactoryBean();
        asfb.setDataSource(dataSource());
        asfb.setMappingResources("hibernate.cfg.xml");
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
        asfb.setHibernateProperties(props);
        return asfb;
    }

}

And finally 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">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/java?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">validate</property>
    <mapping class="local.bb.entities.Users" />
    <mapping class="local.bb.entities.Words" />
  </session-factory>
</hibernate-configuration>

There are no errors but it doesn't read data from database. If I replace SessionFactory sf = (SessionFactory)appContext.getBean("sessionFactory"); in Main.java, with SessionFactory sf = new Configuration().configure().buildSessionFactory(); it works fine. So the problem may be in the Config.java and maybe my approach isn't that good at all? Anyway database connection is working and there are some records inside. Ending this I paste my console result:

    run:
kwi 14, 2015 12:47:58 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1bce4f0a: startup date [Tue Apr 14 12:47:58 CEST 2015]; root of context hierarchy
kwi 14, 2015 12:47:58 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
kwi 14, 2015 12:47:59 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
kwi 14, 2015 12:47:59 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
kwi 14, 2015 12:47:59 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
kwi 14, 2015 12:47:59 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
kwi 14, 2015 12:47:59 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
kwi 14, 2015 12:47:59 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
kwi 14, 2015 12:48:00 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.HSQLDialect
kwi 14, 2015 12:48:00 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
kwi 14, 2015 12:48:00 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
kwi 14, 2015 12:48:00 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.0.0.Final
BUILD SUCCESSFUL (total time: 3 seconds)

your hibernate.hmb.xml should be hibernate cfg file but in your case it's not required as you have created Config.java and in that you declared LocalSessionFactoryBean. In sessionFactory method of Config.java you are passing asfb.setMappingResources("hibernate.cfg.xml");.. setMappingResources method is expecting hbm file ex: mapping.hbm.xml.

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