环境说明: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 中。

spring4+hibernate3的更多相关文章

  1. JEECMS v8 发布,java 开源 CMS 系统

    JEECMSv8 是国内java开源CMS行业知名度最高.用户量最大的站群管理系统,支持栏目模型.内容模型交叉自定义.以及具备支付和财务结算的内容电商为一体:  对于不懂技术的用户来说,只要通过后台的 ...

  2. 搭建SSH框架心得

    <Struts2+Spring4+hibernate3> 工程结构 导入相关jar包:自行网上百度即可,根据环境需要 写dao类 以及实现 package com.icommon.dao; ...

  3. spring3.0.6+hibernate3升级spring4.1.6+hibernate4.3遇到的问题

    1.下面这三个包,在hibernate4中已经废弃了,因为都直接用session来进行很好的事务管理 import org.springframework.orm.hibernate3.Hiberna ...

  4. SSH整合(struts2.3.24+hibernate3.6.10+spring4.3.2+mysql5.5+myeclipse8.5+tomcat6+jdk1.6)

    终于开始了ssh的整合,虽然现在比较推崇的是,ssm(springmvc+spring+mybatis)这种框架搭配确实比ssh有吸引力,因为一方面springmvc本身就是遵循spring标准,所以 ...

  5. Spring4.0整合Hibernate3 .6

    转载自:http://greatwqs.iteye.com/blog/1044271 6.5  Spring整合Hibernate 时至今日,可能极少有J2EE应用会直接以JDBC方式进行持久层访问. ...

  6. 【j2ee spring】27、巴巴荆楚网-整合hibernate4+spring4(2)

    巴巴荆楚网-整合hibernate4+spring4(2) 1.图文项目 2.首先我们引入对应的jar包 这里用的是oracle 11g,所以我们使用的数据库连接jar包是ojdbc6, 的区别就是支 ...

  7. 【j2ee spring】30、巴巴荆楚网-综合hibernate4+spring4(5)分页

    巴巴荆楚网-综合hibernate4+spring4(5)分页 1.图文项目 2.首先我们引入对应的jar包 3.我们配置一下数据库中对应的实体对象 ProductType.java /** * 功能 ...

  8. spring2.5与hibernate3升级后的bug

    手头有一个项目,使用的是struts2 hibernate3 spring2.5 是之前的老项目了,spring与hibernate的版本都比较低 自己看了最新的spring4与hibernate4, ...

  9. Spring4+Hibernate4事务小记

    学习Spring+Hibernate,非常强大的框架,为了追新,就直接从最高版本开始学习了,这要冒很大的风险,因为网上可查到的资料大多是针对旧版本的,比如Spring3,Hibernate3. 根据我 ...

随机推荐

  1. css3 选择器记

    css3 选择器 根据所获取页面中元素的不同,把css3选择器分为五大类: 基本选择器 层次选择器 伪类选择器 动态伪类选择器 目标伪类选择器 语言伪类选择器 UI元素状态伪类选择器 结构伪类选择器 ...

  2. HTTP - Session 机制

    HTTP 是种无状态的协议,即使用 HTTP 协议时,每次发送请求都会产生对应的新响应,协议本身不会保留之前一切的请求或响应报文的信息.这是为了更快地处理大量事务,确保协议的可伸缩性,而特意把 HTT ...

  3. ubuntu(16.04.01)学习-day1

    1.修改root用户密码 sudo passwd root 按提示进行设置. 2.从Ubuntu 16.04开始,用户可以实现改变启动器的位置,可以将启动器移到屏幕底部,但是无法移到右边或顶部.打开终 ...

  4. Ssqlserver 关于Grouping sets

    sqlserver2008之后引入Grouping sets是group by的增强版本,Grouping sets 在遇到多个条件时,聚合是一次性从数据库中取出所有需要操作的数据,在内存中对数据库进 ...

  5. Linux命令(1):cd命令

    1.作用:改变工作目录: 2.格式:cd  [路径]  其中的路径为要改变的工作目录,可为相对路径或绝对路径 3.使用实例:[root@www uclinux]# cd /home/yourname/ ...

  6. ios Swift ! and ?

    swift ?和!之间区别: Swift 引入的最不一样的可能就是 Optional Value 了.在声明时,我们可以通过在类型后面加一个? 来将变量声明为 Optional 的.如果不是 Opti ...

  7. Java开源 开源工作流

    OpenEbXML   点击次数7801 Werkflow   点击次数11181 OSWorkflow   点击次数14988 wfmOpen   点击次数7997 OFBiz   点击次数1234 ...

  8. 实例介绍Cocos2d-x物理引擎:碰撞检测

    碰撞检测是使用物理引擎的一个重要目的,使用物理引擎可以进行精确的碰撞检测,而且执行的效率也很高.在Cocos2d-x 3.x中使用事件派发机制管理碰撞事件,EventListenerPhysicsCo ...

  9. C#中Excel的导入和导出的几种基本方式

    在上一篇(http://www.cnblogs.com/fengchengjushi/p/3369386.html)介绍过,Excel也是数据持久化的一种实现方式.在C#中.我们常常会与Excel文件 ...

  10. OC3_歌词解析

    // // LrcManager.h // OC3_歌词解析 // // Created by zhangxueming on 15/6/15. // Copyright (c) 2015年 zhan ...