Struts2.3.15+Hibernate 4.x+Spring4.x 整合二部曲之上部曲

1 导入jar包

  • 可以复制jar包或maven导入,本文最后会给出github地址

2 导入log4j.properties文件

og4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ###

log4j.rootLogger=debug, stdout 

3 jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssh
jdbc.user=root
jdbc.password=root

4 因为是否需要hibernate.cfg.xml文件,所以Spring和Hibernate整合的方式有两种

4.1 Spring和Hibernate整合的方式一(需要hibernate.cfg.xml文件)

  • 新建domain包,并在doamin包下新建pojo和对应的映射文件

    • Classes.java  
package com.xuweiwei.domain;

import java.io.Serializable;

//班级
public class Classes implements Serializable {
    private Integer cid;
    private String name;
    private String description;

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
    • Classes.hbm.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>
    <!--
        class元素代表持久化类
             name属性为类的全名
             table 表名  默认值:类名
             catalog 数据库的名字
     -->
    <class name="com.xuweiwei.domain.Classes">
        <id name="cid" length="5">
            <generator class="native"></generator>
        </id>
        <property name="name" length="20"></property>
        <property name="description" length="50"></property>
    </class>
</hibernate-mapping>
  • 在src下新建hibernate.cfg.xml文件,并将Classes.hbm.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>
    <!-- 一个sessionFactory代表数据库的一个连接 -->
<session-factory>

    <!--
        方言
        告诉hibernate用什么样的数据库
    -->
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>
    <!--
        validate 加载hibernate时,验证数据库的结构  默认值
        update  加载hibernate时,检查数据库,如果表不存在,则创建,如果存在,则更新
        create  每次加载hiberante,都会创建表
        create-drop  每次加载hiberante,创建,卸载hiberante时,销毁
    -->
    <property name="hbm2ddl.auto">update</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>

    <mapping resource="com/xuweiwei/domain/Classes.hbm.xml"/>

</session-factory>
</hibernate-configuration>
  • 在src下新建applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress InjectionValueTypeInspection -->
<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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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.3.xsd
       http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

     <context:component-scan base-package="com.xuweiwei"/>

     <!--
          配置加载jdbc.properties的类
     -->
     <context:property-placeholder location="classpath*:jdbc.properties"></context:property-placeholder>
     <!--
          配置c3p0连接池
     -->
     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
          <property name="driverClass" value="${jdbc.driverClass}"/>
          <property name="jdbcUrl" value="${jdbc.url}"/>
          <property name="user" value="${jdbc.user}"/>
          <property name="password" value="${jdbc.password}"/>
     </bean>

     <!-- 配置sessionFactory -->
     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
          <property name="dataSource" ref="dataSource"/>
          <property name="configLocations">
               <list>
                    <value>classpath*:hibernate.cfg.xml</value>
               </list>
          </property>

     </bean>

     <!-- 配置事务管理器 -->
     <bean  id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
          <property name="sessionFactory" ref="sessionFactory"/>
     </bean>

     <!-- 开启Spring的编程式事务 -->
     <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>
  • 【说明】:

    • 如果你看过本人的Spring jdbc Template,地址:http://www.cnblogs.com/xuweiweiwoaini/p/8037903.html ,你就会知道其实Spring和Hibernate整合其实和Spring整合jdbc Template是一个套路。
    • 比如我们需要HibernateDaoSupport这个父类,那么HibernateDaoSupport这个父类需要Spring注入SessionFactory对应,这个时候,你可能会想拿直接用SessionFactoryImpl,但是如果你去翻SessionFactoryImpl的源代码,你会发现以下几点:
      • ①我们知道Hibernate是对JDBC的封装,那么你总需要注入DataSource数据源吧,很可惜,SessionFactory并没有提供setter方法或构造方法让我们将数据源DataSource注入,所以,这条路是行不通的。
      • ②既然我们知道SessionFactoryImpl是行不通的,那么在Spring总需要拿到Session吧,怎么办?Spring提供了LocalSessionFactoryBean这个类,这个类可以让我们注入DataSource。  

    • 学过Hibernate知道,我们需要将hibernate.cfg.xml文件加载让Hibernate读取,那么我们需要在LocalSessionFactoryBean中配置一下,将hibernate.cfg.xml文件加载进去。  

    • 所以,我们可以通过configLocations或configLocation将hibernate.cfg.xml文件加载进去。  
    • 我们知道的是如果Spring整合jdbc Template对使用的事务管理器是DataSourceTransactionManager,那么Spring整合Hibernate使用的事务管理器是HibernateTransactionManager,其实在http://www.cnblogs.com/xuweiweiwoaini/p/8037903.html 中我已经说明了。  

  • 新建dao包,在dao包中新建ClassesDao.java和ClassesDaoImpl.java

    • ClassesDao.java  
package com.xuweiwei.dao;

import com.xuweiwei.domain.Classes;

public interface ClassesDao {
    public static final String DAO_NAME= "com.xuweiwei.dao.impl.ClassesDaoImpl";

    public void saveClasses(Classes classes);

}
    • ClassesDaoImpl.java  
package com.xuweiwei.dao.impl;

import com.xuweiwei.dao.ClassesDao;
import com.xuweiwei.domain.Classes;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository(ClassesDao.DAO_NAME)
public class ClassesDaoImpl extends HibernateDaoSupport implements ClassesDao {

    @Resource(name="sessionFactory")
    public void setSessionFactoryDI(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }

    @Override
    public void saveClasses(Classes classes) {
        this.getHibernateTemplate().save(classes);
    }
}
  • 新建service包,并在此包下新建ClassesService.java和ClassesServiceImpl.java

    • ClassesService.java  
package com.xuweiwei.service;

import com.xuweiwei.domain.Classes;

public interface ClassesService {
    public static final String SERVICE_NAME = "com.xuweiwei.service.impl.ClassesServiceImpl";

    public void saveClasses(Classes classes);
}
    • ClassesServiceImpl.java  
package com.xuweiwei.service.impl;

import com.xuweiwei.dao.ClassesDao;
import com.xuweiwei.domain.Classes;
import com.xuweiwei.service.ClassesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
@Service(ClassesService.SERVICE_NAME)
@Transactional
public class ClassesServiceImpl implements ClassesService {

    @Resource(name = ClassesDao.DAO_NAME)
    private ClassesDao classesDao ;

    @Override
    public void saveClasses(Classes classes) {
        classesDao.saveClasses(classes);
    }
}
  • 新建test包,并新建TestHibernate.java
package com.test;

import com.xuweiwei.domain.Classes;
import com.xuweiwei.service.ClassesService;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestHibernate {

    @Resource(name="sessionFactory")
    private SessionFactory sessionFactory;

    @Resource(name = ClassesService.SERVICE_NAME)
    private ClassesService classesService;

    @Test
    public void testSessionFactory(){
        System.out.println(sessionFactory);
    }

    @Test
    public void save(){
        Classes classes = new Classes();
        classes.setName("许威威");
        classes.setDescription("java开发");
        System.out.println(classesService);

        classesService.saveClasses(classes);

    }
}

4.2 Spring和Hibernate整合的方式二(不需要hibernate.cfg.xml文件)

  • 我们知道hibernate.cfg.xml文件除了可以配置一些方言等属性,还可以加载映射文件,如果Spring可以自动加载那些映射文件,并设置方言属性,那么是不是意味着hibernate.cfg.xml没有用了。
  • 还有,我们知道Spring在进行注解开发的时候,设置了一个扫描器,那么我们是否可以联系,只要给定固定的路径,Spring再提供一个扫描器去扫描给定路径下的所有映射文件,这样是不是hibernate.cfg.xml文件的作用完全没有了。
  • 所以,不需要配置hibernate.cfg.xml文件的情况下,applicationContext.xml文件的配置信息如下:
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress InjectionValueTypeInspection -->
<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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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.3.xsd
       http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

     <context:component-scan base-package="com.xuweiwei"/>

     <!--
          配置加载jdbc.properties的类
     -->
     <context:property-placeholder location="classpath*:jdbc.properties"></context:property-placeholder>
     <!--
          配置c3p0连接池
     -->
     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
          <property name="driverClass" value="${jdbc.driverClass}"/>
          <property name="jdbcUrl" value="${jdbc.url}"/>
          <property name="user" value="${jdbc.user}"/>
          <property name="password" value="${jdbc.password}"/>
     </bean>

     <!-- 配置sessionFactory -->
     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
          <property name="dataSource" ref="dataSource"/>
          <property name="mappingDirectoryLocations">
               <!--
                    mappingDirectoryLocations:可以扫描domain包下的所有映射文件
               -->
               <list>
                    <value>classpath*:com/xuweiwei/domain</value>
               </list>
          </property>
          <property name="hibernateProperties">
               <props>
                    <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
                    <prop key="hbm2ddl.auto">update</prop>
                    <prop key="show_sql">true</prop>
                    <prop key="format_sql">true</prop>
               </props>
          </property>

     </bean>

     <!-- 配置事务管理器 -->
     <bean  id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
          <property name="sessionFactory" ref="sessionFactory"/>
     </bean>

     <!-- 开启Spring的编程式事务 -->
     <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>
  • 其他步骤和4.1相同

5 项目地址

时间: 2024-07-29 08:13:36

Struts2.3.15+Hibernate 4.x+Spring4.x 整合二部曲之上部曲的相关文章

Struts2,Spring, Hibernate三大框架SSH的整合步骤

整合步骤 创建web工程 引入相应的jar包 整合spring和hibernate框架 编写实体类pojo和hbm.xml文件 编写bean-base.xml文件 <!-- 1) 连接池实例 -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass"

[SSH] Eclipse+Struts2+Hibernate4+Spring4的整合

在前面Struts2和Hibernate4的整合基础上,对Spring4进行整合,网上参考的大概都是Spring4+Hibernate3或者基于MyEclispe的,这里把自己研究后的配置和大家分享一下. 本次相关的版本如下: Spring : spring-framework-4.0.1.RELEASE 1.将相关的jar包导入: 1.1libs目录下包含所有的jar包(不需要复制结尾为sources和javadoc的jar包)到SSHProject项目的lib目录 1.2 Hibernate

转载:Struts2.3.15.1升级总结

转载网址:http://blog.csdn.net/amosryan/article/details/10350481 由于大家都懂的原因,涉struts2的项目需要将struts2相关包升级至2.3.15.1.今将升级方法和常见问题解决简单总结如下. 一.基本升级操作 1. 获取Struts2.3.15.1jar包 从Struts官网下载struts2.3.15.1发布包: http://apache.fayea.com/apache-mirror//struts/library/struts

MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合(转载)

孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(八)--Mybatis3.x与Spring4.x整合 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: mvn archetype:create -DgroupId=me.gacl -DartifactId=spring4-mybatis3 -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false 如下图所示: 创建好的项目如下

项目ITP(五) spring4.0 整合 Quartz 实现任务调度

前言 系列文章:[传送门] 项目需求: 二维码推送到一体机上,给学生签到扫描用.然后需要的是 上课前20分钟 ,幸好在帮带我的学长做 p2p 的时候,接触过.自然 quartz 是首选.所以我就配置了下,搞了个小样例给大家. 正文 spring4.0 整合 Quartz 实现任务调度.这是期末项目的最后一篇,剩下到暑假吧.  Quartz 介绍 Quartz is a full-featured, open source job scheduling service that can be in

项目ITP(六) spring4.0 整合 Quartz 实现动态任务调度

前言 系列文章:[传送门] 项目需求: http://www.cnblogs.com/Alandre/p/3733249.html 上一博客写的是基本调度,后来这只能用于,像每天定个时间 进行数据库备份.但是,远远不能在上次的需求上实现.所以需要实现spring4.0 整合 Quartz 实现动态任务调度. 正文 spring4.0 整合 Quartz 实现任务调度.这真是期末项目的最后一篇,剩下到暑假吧.  Quartz 介绍 Quartz is a full-featured, open s

Struts 2.x 与Spring4.x整合出现:No mapping found for dependency [type=java.lang.String, name=&#39;actionPackages...

Struts2.16与Spring4.x整合出错: Caused by: java.lang.RuntimeException: com.opensymphony.xwork2.inject.DependencyException: com.opensymphony.xwork2.inject.ContainerImpl$MissingDependencyException: No mapping found for dependency [type=java.lang.String, name

[CXF REST标准实战系列] 二、Spring4.0 整合 CXF3.0,实现测试接口(转)

转自:[CXF REST标准实战系列] 二.Spring4.0 整合 CXF3.0,实现测试接口 文章Points: 1.介绍RESTful架构风格 2.Spring配置CXF 3.三层初设计,实现WebService接口层 4.撰写HTTPClient 客户端,并实现简单调用 介绍RESTful架构风格 REST是REST之父Roy Thomas创造的,当时提出来了REST的6个特点:客户端-服务器的.无状态的.可缓存的.统一接口.分层系统和按需编码.其具有跨语言和跨平台的优势. REST是一

15.文件系统——软RAID的实现(二)(mdadm,watch, RAID1)

前文介绍了使用mdadm命令穿件软RAID0的过程,本章将继续演示RAID1和RAID5的创建过程. 在演示具体的创建过程之前,需要进一步介绍madam命令可用的选项: -f:把某设备指定为模拟损坏 -r:把损坏的设备移除 -a:新增一个设备到阵列中 一.创建一个大小为1G的RAID1: 对RAID1来说,其利用率只有50%,故要使RAID1的有效空间为1G,就需要两个1G的分区,其创建过程如下: [[email protected] backup]# fdisk/dev/sdc WARNING