日期:2014-05-19  浏览次数:20730 次

Spring3+Hibernate4该怎么注入SessionFactory?
刚学Spring,碰到一个问题,看网上帖子说已经废弃HibernateTemplate了,但是没找到相关的配置,经实验确实用hibernate3.6.10可以运行的程序改到hibernate4.1的时候会出错,想问下该怎么使用?
写了一个简单的小程序,想问下具体该怎么改动呢?

下面是Spring配置
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"在使用hibernate4.1的时候这里的hibernate3我是改成hibernate4的
XML code

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/spring_test" />
        <property name="username" value="root" />
        <property name="password" value="1234" />
    </bean>

    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="mappingResources">
            <list>
                <value>com/xlinspace/www/entity/User.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
                hibernate.show_sql=true
                hibernate.hbm2ddl.auto=update
                javax.persistence.validation.mode=none
              </value>
        </property>
    </bean>
        <bean id="userDao" class="com.xlinspace.www.dao.UserDao">
        <property name="sessionFactory" ref="mySessionFactory"></property>
    </bean>



下面简单的DAO代码
Java code

public class UserDao {

    private HibernateTemplate ht = null;
    private SessionFactory sessionFactory;
    
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    private HibernateTemplate getHibernateTemplate(){
        if(ht==null){
            ht = new HibernateTemplate(getSessionFactory());
        }
        return ht;
    }
    
    public Integer save(User user){
        return (Integer)getHibernateTemplate().save(user);
//        Session session = getSessionFactory().getCurrentSession(); 实验不能这么取
//        session.beginTransaction();
//        session.save(user);
//        session.getTransaction().commit();
    }
}




下面是简单的存个数据
Java code

public class UseUser {

    public static void main(String[] args){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        
        User user = new User();    
        user.setAge(10);
        user.setName("Lucky");
                
        UserDao userDao = (UserDao)ctx.getBean("userDao");
        userDao.save(user);
    }
}



------解决方案--------------------
hibernate4还木有用过啊,去下个官方文档,里面肯定有整合spring的
------解决方案--------------------
hibernate3的飘过。。。