Struts2+Hibernate3.2+Sprint2.5整合

本文详细介绍了如何使用MyEclipse、Spring、Hibernate和数据库连接池(Proxool)进行数据库操作的整合流程,包括配置数据库连接、创建项目、整合Spring和Hibernate,以及编写测试代码以确保集成成功。


Hibernate使用数据库连接池、

MyEclipse6.5  Tomcat6.0

 

创建项目,

 

 

 

 

 

 

整合Hibernate

右键项目,MyEclipse—>AddHibernate Capabilities

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

使用Spring管理,把勾去掉

 

 

 

 

 

 

 

 

 

 

整合Spring2.5

右键项目,MyEclipse—>AddSpringCapabilities

 

 

 

 

 

导入数据库连接池包:proxool-0.9.1.jar  proxool-cglib.jar

和数据库驱动包 :mysql-connector-java-5.0.8-bin.jar

 

 

 

 

编写src/jdbc.properties文件

 

db.driver=com.mysql.jdbc.Driver

db.url=jdbc:mysql://localhost:3306/tuanwei3

db.user=root

db.password=123456

db.alias=MySqlPool

db.houseKeepingTestSql=select 1

db.characterEncoding=UTF-8

db.maximumConnectionCount=50

db.minimumConnectionCount=20

 

编写applicationContext.xml文件

<?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:jee="http://www.springframework.org/schema/jee"xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd

                  http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd

                  http://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-2.5.xsd

                  http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"

    default-lazy-init="true">

    <!-- 关于spring启动的优化 default-lazy-init="true"-->

   

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

    <property name="location">

        <value>classpath:jdbc.properties</value>

       </property>

    </bean>   

    <!-- 使用proxool连接池配置数据源 -->

    <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">     

       <property name="driver" value="${db.driver}"/>

       <property name="driverUrl" value="${db.url}"/>

       <property name="user" value="${db.user}"/>

       <property name="password" value="${db.password}"/>

       <property name="alias" value="${db.alias}"/>

       <property name="houseKeepingTestSql" value="${db.houseKeepingTestSql}"/>

       <property name="maximumConnectionCount" value="${db.maximumConnectionCount}"/>

       <property name="minimumConnectionCount" value="${db.minimumConnectionCount}"/>

       <property name="delegateProperties" value="characterEncoding=${db.characterEncoding}"/>

       <!--

           alias  别名名字

          houseKeepingTestSql=select CURRENT_DATE当连接为空闲连接时,

            用此条sql语句来测试是否空闲中。如果sql语句不存在,那么测试将被忽略。  

           maximum-connection-lifetime    最大连接生命周期 默认值:4小时

           maximum-active-time:      最大活动时间    默认值:5分钟

           maximum-connection-count   最大连接数     默认值:15个

           minimum-connection-count   最小连接数     默认值:5个

        -->

    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

       <property name="dataSource" ref="dataSource"/>

       <!-- hibernate配置文件所在地 -->

       <property name="mappingDirectoryLocations">

           <list>

           <value>classpath:/Junit/test</value>

           </list>

       </property>

       <!-- 配置hibernate属性 如第一个方言等-->

       <!--

           1.hibernate.dialect Hibernate SQL方言  表示连接那种数据库

           2.hibernate.query.substitutions

              你可以使用hibernate.query.substitutions定义新的Hibernate查询短语。比如说:

           hibernate.query.substitutions true 1, false 0

              这个配置意思是当你在Hibernate里面输入true的时候,Hibernate会转化为1插入数据库,

              当你在Hibernate里面输入false的时候,Hibernate会转化为0插入数据库,后面的Y,N同理。

              对于某些数据库,例如Oracle来说,没有boolean数据类型,就是采用1代表true,0代表false,

              因此使用这个配置在Hibernate里面直接用true/false会非常直观。

           hibernate.query.substitutions toLowercase=LOWER

              这可以让你重新命名SQL的LOWER函数。

           3.hibernate.jdbc.batch_size 一个非零值,会开启Hibernate使用JDBC2的批量更新功能取值. 建议值在 5 和 30之间。

           4.hibernate.cache.provider_class 指定一个自定义的CacheProvider缓存提供者的类名.取值. classname.of.CacheProvider

           5.hibernate.cache.provider_configuration_file_resource_pathhibernate缓存文件路径

            6.update如果数据库中不存在表则生成,存在如果有增加自动增加,开发使用update,生产一般不设置

             -->

       <property name="hibernateProperties">

           <value>

           hibernate.hbm2ddl.auto

           hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect

           hibernate.query.substitutions=true 1, false 0

           hibernate.jdbc.batch_size=20

           hibernate.hbm2ddl.auto=update

           hibernate.show_sql=true

           hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider

           hibernate.cache.provider_configuration_file_resource_path=/ehcache-hibernate.xml

           </value>

           <!--hibernate.cache.provider_configuration_file_resource_path

              指定缓存文件路径和文件名

            -->

       </property>

    </bean>

   

    <!-- 事务配置 配置事务管理器-->

    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

       <property name="sessionFactory" ref="sessionFactory" />

    </bean>

    <!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入

        base-package="com.wlb" 把com.wlb下的包都纳入管理

    -->

    <context:component-scanbase-package="Junit.test" />

   

    <!-- 使用annotation定义事务 采用注解的方式管理 如:@Server@Controller @Repository @component-->

    <tx:annotation-driventransaction-manager="txManager" />

</beans>

 

 

 

编写 Junit 测试Hibernate与Sprint集成

 

新建包 JUnit/test  application.xml文件配置中注意包名要一致

BaseDao.java类

package JUnit.test;

 

public interface BaseDao {

    public void save(Objectobj);

}

 

BaseDaoImpl.java类

package JUnit.test;

 

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

import org.springframework.transaction.annotation.Transactional;

 

@Repository

@Transactional

public class BaseDaoImpl implements BaseDao {

   

    @Autowired

    protected SessionFactory sessionFactory;

   

    public void setSessionFactory(SessionFactory sessionFactory){

       this.sessionFactory = sessionFactory;

    }

   

    public Session getSession(){

       return sessionFactory.getCurrentSession();

    }

   

    public void save(Object obj){

       getSession().save(obj);

    }

 

}

 

 

 

 

 

 

Person.java实体类

package Junit.test;

import java.io.Serializable;

public class Person implements Serializable {

    private Long id;

    private String name;

    private int age;

    public Long getId() {

       return id;

    }

    public void setId(Long id) {

       this.id = id;

    }

    public String getName() {

       return name;

    }

    public void setName(String name) {

       this.name = name;

    }

    public int getAge() {

       return age;

    }

    public void setAge(int age) {

       this.age = age;

    }

}

Person.hbm.xml hibernate配置文件

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD//EN"

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

 

<hibernate-mapping package="Junit.test">

    <class

       name="Person"

       table="PERSON"

    >

       <id

           name="id"

           type="java.lang.Long"

           column="PERSON_ID"

       >

           <generator class="native"/>

       </id>

       <property

           name="name"

           column="name"

           type="java.lang.String"

           length="20"

       />

       <property

           name="age"

           column="age"

           type="java.lang.Integer"

           length="10"

       />

    </class>  

</hibernate-mapping>

 

TestDao.java测试文件

package JUnit.test;

 

import org.junit.AfterClass;

import org.junit.BeforeClass;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

import JUnit.test.Person;

 

 

public class TestDao {

 

    private static ApplicationContext cxt;

    private static BaseDao baseDao;

 

    @BeforeClass

    public static void setUpBeforeClass() throws Exception {

       try{

           cxt = new ClassPathXmlApplicationContext("applicationContext.xml");

           baseDao = (BaseDao)cxt.getBean("baseDaoImpl");

       }catch(Exception e){

           e.getStackTrace();

       }

          

    }

 

    @AfterClass

    public static void tearDownAfterClass() throws Exception {

    }

 

    @Test

    public void testSave(){

       for(int i=0;i<20;i++){

           Person ps = new Person();

           ps.setName("chenbo"+i);

           ps.setAge(i);

           baseDao.save(ps);

       }

    }

}

 

在数据库中新建指定的数据库,运行TestDao保存数据进数据库,集成成功。

 

集成Struts2.0.

使用Struts2.0.11

导入包commons-io-1.3.2.jar  freemarker-2.3.8.jar  ognl-2.6.11.jar

Struts2-core-2.0.11.jar  xwork-2.0.4.jar  struts2-spring-plugin-2.0.11.jar

看有无重复的jar包,去掉(否则会引起冲突报错),如:asm.2.2.3.jar等

可以通过Referencedlibraries 右键,

查看buildi path-à configure build path 安字母顺序排序看有无重复

 

在src下新建struts.xml文件 注意要 写<struts></struts>

 

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

<!DOCTYPE struts PUBLIC

    "-//ApacheSoftware Foundation//DTD Struts Configuration 2.1//EN"

    "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

 

</struts>

 

在web.xml 文件中声明struts2 过滤器

<!-- struts2过滤器 -->

    <filter>

       <filter-name>struts2</filter-name>

    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>

    </filter>

 

<filter-mapping>

       <filter-name>struts2</filter-name>

       <url-pattern>*.do</url-pattern>

</filter-mapping>

 

 

在web.xml文件中声明Spring 监听器

<!-- spring容器实例化,声明spring的监听器 -->

    <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

在web.xml 文件中配置

    <!-- 指定spring配置文件 -->

    <context-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>

           classpath:applicationContext.xml

       </param-value>

    </context-param>

 

Src下配置struts.properties

#struts接收的后缀名

struts.action.extension=do

#把struts2交给spring管理,指定Struts 2默认的ObjectFactory Bean,该属性默认值是spring。

struts.objectFactory=spring

#允许动态方法调用

struts.enable.DynamicMethodInvocation=false

#是否为strtus开发模式,如果设置该属性为true,则可以在应用出错时显示更多、更友好的出错提示。

struts.devMode=false

#默认的国际化地区信息

struts.locale=zh_CN

#国际化信息内码

#struts.i18n.encoding=GBK

#默认的UI template主题,关于struts2页面布局

struts.ui.theme=simple

#该属性指定Struts 2应用所需要的国际化资源文件,如果有多份国际化资源文件,则多个资源文件的文件名以英文逗号(,)隔开。

#struts.custom.i18n.resources=i18n

#该属性指定视图主题所需要模板文件的位置,该属性的默认值是template,即默认加载template路径下的模板文件。

struts.ui.templateDir=/WEB-INF/template

# 该属性指定上传文件的临时保存路径,该属性的默认值是javax.servlet.context.tempdir

#struts.multipart.saveDir=temp/

# multipart请求信息的最大尺寸(文件上传用)

struts.multipart.maxSize=8388608

#该属性设置Struts 2是否允许在Action名中使用斜线

struts.enable.SlashesInActionNames=true

 

Struts2+Hibernate3.2+Sprint2.5 整合 完成

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值