Hibernate和Spring的整合

来源:互联网 发布:餐厅绩效指标数据 编辑:程序博客网 时间:2024/05/16 00:55

    简介:

      Spring与Hibernate整合,到底整合什么呢?Spring主要是管理Hibernate的Session Factory以及事务支持等。我们在Hibernate中需要自己创建SessionFactory实例,这显然不是很好的方法。

      在Spring中可以通过配置文件,向Dao中注入SessionFactory,Spring的Ioc容器则提供了更好的管理方式,它不仅以声明式的方式配置了SessionFactory实例,也可充分利用Ioc容器的作用,为SessionFactory注入数据源。还有事务处理,我们业务代码不需要考虑事务,只需要在配置文件配置事务即可。

     Spring提供了对多种数据库访问DAO技术支持,包括Hibernate,JDO,TopLink,iBatis等。对不同的数据库访问Spring采用了相同的访问模式。Spring提供HibernateDaoSupport类来实现Hibernate的持久层访问技术。

      一旦在Spring的Ioc容器中配置了SessionFactory Bean,它将随应用的启动而加载,可以充分利用Ioc容器的功能,将SessionFactory Bean的注入任何Bean,比如DAO组件,以声明式的方式管理SessionFactory实例,可以让应用在不同数据源之间切换。如果应用更换数据库等持久层资源,只需对配置文件进行简单修改即可。


这里有个事务处理的配置,放到下篇文章SS2H三者整合中再作详细介绍。


实例演示:

springHibernateWeb



web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>springHibernateWeb</display-name>  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>WEB-INF/applicationContext.xml</param-value>  </context-param>  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans><!-- 配置SessionFactory --><bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="configLocation" value="WEB-INF/hibernate.cfg.xml"></property></bean><bean id="dao" class="dao.CustomerDaoJdbc"><property name="sessionFactory" ref="sessionFactory"></property></bean></beans>

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="connection.username">hncu</property><property name=""></property><property name="connection.url">jdbc:mysql://127.0.0.1:3306/mydb</property><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="myeclipse.connection.profile">mysql1</property><property name="connection.password">1234</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><mapping resource="bean/Customer.hib.xml" /></session-factory></hibernate-configuration>

Customer.hib.xml

<?xml version="1.0" encoding="utf-8"?>  <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  <!-- 根元素:<hibernate-mapping>,每一个hbm.xml文件都有唯一的一个根元素,包含一些可选的属性 --><hibernate-mapping > <!-- name:持久化类(或者接口)的Java全限定名,如果这个属性不存在,则Hibernate将假定这是一个非POJO的实体映射 --><class name="bean.Customer"  table="customers" catalog="mydb"><id name="customerId" type="java.lang.String"><column name="customerId" length="8"></column><generator class="assigned"></generator></id><property name="name" type="java.lang.String"><column name="name" length="15"></column></property><property name="phone" type="java.lang.String"><column name="phone" length="16"></column></property></class></hibernate-mapping>

Customer.java

package bean;public class Customer {private String customerId;private String name;private String phone;public String getCustomerId() {return customerId;}public void setCustomerId(String customerId) {this.customerId = customerId;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}}

CustomerDaoJdbc.java

package dao;import java.util.ArrayList;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import bean.Customer;public class CustomerDaoJdbc extends HibernateDaoSupport{/* 返回单个对象 */public Customer queryCustomerById(Customer customer){customer=(Customer) this.getHibernateTemplate().get(Customer.class, customer.getCustomerId());return customer;}public List<Customer> queryAllCustomer(){List<Customer> list=new ArrayList<Customer>();Session session=this.getSession();String hql="from Customer";Query query=session.createQuery(hql);list=query.list();return list;}}

index.jsp

<%@page import="bean.Customer"%><%@page import="java.util.List"%><%@page import="dao.CustomerDaoJdbc"%><%@page import="org.springframework.context.ApplicationContext"%><%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><% //这里直接在前台页面访问了dao,获取了数据。(按理应该要访问servlet,这里省略了)ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(getServletContext());CustomerDaoJdbc dao=(CustomerDaoJdbc)ctx.getBean("dao");List<Customer> customers=dao.queryAllCustomer();request.setAttribute("customers", customers);%><body><table>      <tr>        <td>编号</td>        <td>姓名</td>        <td>电话</td>      </tr>      <c:forEach items="${customers}" var="customer">      <tr>      <td>${customer.customerId}</td><td>${customer.name}</td><td>${customer.phone}</td>      </tr>      </c:forEach> </table></body></html>


查询结果:

数据库中记录:



sql记录:

/* CREATE DATABASE mydb CHARACTER  SET utf8;; */use mydb;create table customers(  customerID char(8) primary key,  name char(15) default NULL,  phone char(16) default NULL);insert into customers values('CROFJL01','Jill Croft','(213) 555-8917');insert into customers values('ERKEMY01','Molly Erkel','(604) 555-9825');insert into customers values('FIELKE01','Kate Field','(718) 555-9283');insert into customers values('FROBJN01','John Froberger','(212) 555-0743');insert into customers values('GADEDE01','Dave Grade','(914) 555-1135');insert into customers values('KJHTYE01','Mile Roof','(733) 555-1237');insert into customers values('ERKEMY02','Molly Wolf','(763) 555-1825');insert into customers values('FIELKE02','Kate Right','(302) 555-3692');insert into customers values('FROBJN02','Hward Draw','(382) 555-6723');insert into customers values('GADEDE02','Dave Brook','(271) 555-3927');




0 0
原创粉丝点击