hibernate+spring的整合思路加实例(配图解) (一)

2014-11-24 10:11:53 · 作者: · 浏览: 0

首先框架整合我感觉最难的是jar包的引入。因为不同框架的jar容易产生冲突。如果能排除这个因素我想说整合框架还是相对比较容易的。

我整合的框架的一个思想就是:各司其职。因为每个框架处理的事务或者是层次是不一样的。

也就说我们可以这么想。Hibernate就是操纵数据库的是持久层的。而spring就是利用ioc的bean对类进行实例化化的。Spring就是一个容器。

基于这个思想我想到的就是最传统的思想。我写一个往数据库里面添加记录的实例。

所以我整合的步骤就是四步

第一步:搭建hibernate环境(包括引入hibernate的jar,包配置数据源,建立类和表的映射),为什么这么做。我觉得hibernate是最重要的。因为没有spring不影响我往数据里面添加记录。Spring仅仅是一个容器。

第二步:配置spring的环境(引入jar和写一个spring.XML的配置信息)

第三步:在spring里面注册hibernate。

第四步:测试

那么我们按照这个步骤。(我的是spring3.2和hibernate3.2这里两个版本一起很少见。但是只要里面jar不冲突是一点问题没有)

首先我们引入所有jar包:这里我就顺便把spring和hibernate 的全引进去了。

\


接着就是写hibernate.cgf.xml

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

mysql

jdbc:mysql://127.0.0.1:3306/test

root

330127

com.mysql.jdbc.Driver

org.hibernate.dialect.MySQLDialect

update//上面都是配置数据源,和本级数据库建立连接的。

//把映射表xml往这里注册。

那么我们写Person.hbm.xml

< xml version="1.0" >

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

//person映射类类名

当然我们写对应的person映射类类

package com.fish.dao;

publicclass Person {

String name;

String passwrod;

Integer id;

public String getName() {

returnname;

}

publicvoid setName(String name) {

this.name = name;

}

public String getPasswrod() {

returnpasswrod;

}

publicvoid setPasswrod(String passwrod) {

this.passwrod = passwrod;

}

public Integer getId() {

returnid;

}

publicvoid setId(Integer id) {

this.id = id;

}

}

上面是对hibernate搭建。

接着我们来配置xml

< xml version="1.0" encoding="UTF-8" >

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.xsd">

//该bean是初始化person类的。而且往里面设置了值,就是以后网表中的数据,如果能成功数据库就会显示、tom和330127

class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

//这个bean是spring内部的一个类 // LocalSessionFactoryBean这个类实例化我们可以得到sessionfactory。该类中有个属性configLocation通过这个属性我们就可以hibernate.cfg.xml建立联系了。

下面我们来一个测试类。

package com.fish.dao;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

publicclass Test {

publicstaticvoid main(String[] args) {

// Configuration configuration=new Configuration();

// configuration.configure("hibernate.cfg.xml");

//

// SessionFactory factory=configuration.buildSessionFactory();

// Session session=factory.openSession();

//

// Person person=new Person();

// person.setName("yaku");

// person.set