spring4+hibernate3

环境说明:spring4.0+hibernate3

数据库:oracle

连接池:c3p0

项目结构:

lib中的jar:

一、配置spring.xml

说明:这里采用的配置模式将hibernateTemplate注入至类NewsDaoImpl中。在本文的“附”中介绍的是在类NewsDaoImpl自动装载hibernateTemplate

<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- 引入外部文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
     <property name="driverClass">  
         <value>${driverName}</value>  
     </property>   
     <property name="jdbcUrl">  
         <value>${url}</value>  
     </property>  
     <property name="user">  
         <value>${name}</value>  
     </property>  
     <property name="password">  
         <value>${pwd}</value>  
     </property>  
     <property name="maxPoolSize">  
         <value>40</value>  
     </property>  
     <property name="minPoolSize">  
         <value>10</value>  
     </property>   
     <property name="initialPoolSize">  
         <value>10</value>  
     </property>  
</bean> 

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="hibernateProperties">
        <props>
           <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
           <prop key="hibernate.show_sql">true</prop>
           <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
    <property name="mappingResources">
        <list>
           <value>com/chen/vo/News.hbm.xml</value>
        </list>
    </property>
</bean>

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

<bean id="newsDaoImpl" class="com.chen.dao.NewsDaoImpl">
    <property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean> 
    
<!-- 开启注解模式 -->
<context:annotation-config/>
<!-- 扫包(使用“注解模式”需要此配置)。服务器在启动时会扫描base-package所指定的包,并将相应的bean注入ApplicationContext容器。 -->
<context:component-scan base-package="com.chen"></context:component-scan>

</beans>

二、配置News.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- 指定Hibernate映射文件的DTD信息 -->
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- hibernate-mapping是映射文件的根源素 -->
<hibernate-mapping>
<!-- 每个class对应一个持久化对象 -->
<class name="com.chen.vo.News" table="news_table">
<!-- id元素定义持久化类的标识属性 -->
<id name="id">
<generator class="sequence">
<param name="sequence">seq_news</param>
</generator>
</id>
<!-- property元素定义常规属性 -->
<property name="title"/>
<property name="content"/>
</class>
</hibernate-mapping>

三、创建vo

package com.chen.vo;

public class News
{
   //消息类的标识属性
   private Integer id;
   //消息标题
   private String title;
   //消息内容
   private String content;
   //id属性的setter和getter方法
   public void setId(Integer id)
   {
       this.id=id;
   }
   public Integer getId()
   {
       return this.id;
   }
   //title属性的setter和getter方法
   public void setTitle(String title)
   {
       this.title=title;
   }
   public String getTitle()
   { 
       return this.title; 
   }
   //content 属性的setter和getter方法
   public void setContent(String content)
   {
       this.content=content;
   }
   public String getContent()
   {
       return this.content;
   }
   
    @Override
    public String toString() {
        return "News [id=" + id + ", title=" + title + ", content=" + content + "]";
    }
   
}

四、创建模型层

package com.chen.dao;

import java.util.List;

import com.chen.vo.News;

public interface NewsDao {
    public abstract List<News> listNews();
    public abstract News findNewsById(int id);
    public abstract News findNewsById2(int id);
    public abstract void saveNews(News news);
    public abstract void deteleNews(News news);
    public abstract void updateNews(News news);
}
package com.chen.dao;

import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.chen.vo.News;
@Repository("newsDaoImpl")
public class NewsDaoImpl implements NewsDao{
    // 设置hibernateTemplate属性  
    private HibernateTemplate hibernateTemplate; 
    // 必须设置set方法  
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {  
        this.hibernateTemplate = hibernateTemplate;  
    }  

    @Override
    public List<News> listNews() {
        List<News> entities = hibernateTemplate.find("from News");  
        return entities;  
    }

    @Override
    public News findNewsById(int id) {
        List<News> entitise = hibernateTemplate.find("from News where id=" + id);  
        if (entitise.size() > 0) {  
            News entity = entitise.get(0);  
            return entity;  
        }  
        return null;  
    }

    @Override
    public News findNewsById2(int id) {
        return hibernateTemplate.load(News.class, id);
    }

    @Override
    public void saveNews(News news) {
        hibernateTemplate.saveOrUpdate(news);
        
    }

    @Override
    public void deteleNews(News news) {
        hibernateTemplate.delete(news);
        
    }

    @Override
    public void updateNews(News news) {
        hibernateTemplate.saveOrUpdate(news);
        
    }


}

五、测试

package com.chen.test;

import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.chen.dao.NewsDao;
import com.chen.vo.News;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml") 
public class Spring_HibernateTest {
    
    //自动装载
    @Resource
    NewsDao newsDaoImpl;
    
    @Test
    public void getHibernateTemplate(){
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:spring.xml"); 
        System.out.println(applicationContext.getBean("hibernateTemplate"));
       //org.springframework.orm.hibernate3.HibernateTemplate@e79f7a
    }
    @Test
    public void listNews(){
        List<News> list = newsDaoImpl.listNews();
        System.out.println(list);
    }
    @Test
    public void otherListNews(){
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:spring.xml"); 
        HibernateTemplate hibernateTemplate = (HibernateTemplate) applicationContext.getBean("hibernateTemplate");
        List<News> entities = hibernateTemplate.find("from News");
        System.out.println(entities);
    }
    @Test
    public void findNewsById(){
        News n = newsDaoImpl.findNewsById(2);
        System.out.println(n);
    }
    //org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    @Test
    public void findNewById2(){
        News n = newsDaoImpl.findNewsById2(2);
        System.out.println(n);
    }
    @Test
    public void saveNews(){
        News n = new News();
        n.setTitle("t_Title");
        n.setContent("t_content");
        newsDaoImpl.saveNews(n);
    }
    @Test
    public void deteleNews(){
        News n = new News();
        n.setId(6);
        newsDaoImpl.deteleNews(n);
    }
    @Test
    public void updateNews(){
        News n = newsDaoImpl.findNewsById(2);
        n.setTitle("a");
        newsDaoImpl.updateNews(n);
    }
}

 小结:这里采用findNewById2查询bean信息会报异常:org.hibernate.LazyInitializationException: could not initialize proxy - no Session。具体原因及解决方法见“”。


附:在NewsDaoImpl 使用@Resource--自动装载hibernateTemplate

1.修改spring.xml——即删除原来的“将hibernateTemplate 注入到类NewsDaoImpl 中的配置代码”

<?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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- 引入外部文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
     <property name="driverClass">  
         <value>${driverName}</value>  
     </property>   
     <property name="jdbcUrl">  
         <value>${url}</value>  
     </property>  
     <property name="user">  
         <value>${name}</value>  
     </property>  
     <property name="password">  
         <value>${pwd}</value>  
     </property>  
     <property name="maxPoolSize">  
         <value>40</value>  
     </property>  
     <property name="minPoolSize">  
         <value>10</value>  
     </property>   
     <property name="initialPoolSize">  
         <value>10</value>  
     </property>  
</bean> 

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="hibernateProperties">
        <props>
           <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
           <prop key="hibernate.show_sql">true</prop>
           <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
    <property name="mappingResources">
        <list>
           <value>com/chen/vo/News.hbm.xml</value>
        </list>
    </property>
</bean>

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

<!-- 开启注解模式 -->
<context:annotation-config/>
<!-- 扫包(使用“注解模式”需要此配置)。服务器在启动时会扫描base-package所指定的包,并将相应的bean注入ApplicationContext容器。 -->
<context:component-scan base-package="com.chen"></context:component-scan>

</beans>

 

2.修改NewsDaoImpl

package com.chen.dao;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.chen.vo.News;
@Repository("newsDaoImpl")
public class NewsDaoImpl implements NewsDao{
    @Resource
    private HibernateTemplate hibernateTemplate; 
    
    @Override
    public List<News> listNews() {
        List<News> entities = hibernateTemplate.find("from News");  
        return entities;  
    }

    @Override
    public News findNewsById(int id) {
        List<News> entitise = hibernateTemplate.find("from News where id=" + id);  
        if (entitise.size() > 0) {  
            News entity = entitise.get(0);  
            return entity;  
        }  
        return null;  
    }

    @Override
    public News findNewsById2(int id) {
        return hibernateTemplate.load(News.class, id);
    }

    @Override
    public void saveNews(News news) {
        hibernateTemplate.saveOrUpdate(news);
        
    }

    @Override
    public void deteleNews(News news) {
        hibernateTemplate.delete(news);
        
    }

    @Override
    public void updateNews(News news) {
        hibernateTemplate.saveOrUpdate(news);
        
    }


}

重启服务器,在初始化ApplicationContext时会将hibernateTemplate自动装载到类NewsDaoImpl 中。

posted @ 2015-10-05 22:07  Tom1997  阅读(1534)  评论(0编辑  收藏  举报