SpringMVC4+Spring4+Hibernate4框架整合

最近项目需求,搭建了SSH框架,整合Spring4+SpringMVC+Hibernate4框架实例。 在网上看了很多文档,踩了很多雷,最终都不是自己想要的,经过一个星期努力,最终搭建成了,和自己预期的差不多还算满意。(我使用的JDK6,mysql5),下面来看代码和实例,希望能帮到大家。有需要demo的可以下载哦(最下面有连接)。

ssh框架所需的jar包:


antlr-2.7.7.jar
aspectjrt-1.8.9.jar
aspectjweaver-1.8.9.jar
c3p0-0.9.2.1.jar
commons-beanutils-1.8.3.jar
commons-collections-3.2.jar
commons-httpclient-3.1.jar
commons-lang-2.6.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
ezmorph-1.0.6.jar
hibernate-c3p0-4.3.11.Final.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.11.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
json-lib-2.4-jdk15.jar
jstl.jar
log4j-1.2.17.jar
mchange-commons-java-0.2.3.4.jar
mysql-connector-java-5.1.9-bin.jar
spring-aop-4.3.13.RELEASE.jar
spring-beans-4.3.13.RELEASE.jar
spring-context-4.3.13.RELEASE.jar
spring-context-support-4.3.13.RELEASE.jar
spring-core-4.3.13.RELEASE.jar
spring-expression-4.3.13.RELEASE.jar
spring-jdbc-4.3.13.RELEASE.jar
spring-orm-4.3.13.RELEASE.jar
spring-test-4.3.13.RELEASE.jar
spring-tx-4.3.13.RELEASE.jar
spring-web-4.3.13.RELEASE.jar
spring-webmvc-4.3.13.RELEASE.jar

目录结构

src下创建下面几个文件。
applicationContext.xml
db.properties
springmvc.xml
SpringMVC4+Spring4+Hibernate4框架整合_第1张图片

web.xml配置


<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>

     
    <context-param>  
        <param-name>contextConfigLocationparam-name>  
        <param-value>classpath:applicationContext.xmlparam-value>  
    context-param>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
    listener> 

      
    <servlet>  
        <servlet-name>dispatcherServletservlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
          
        <init-param>  
            <param-name>contextConfigLocationparam-name>  
            <param-value>classpath:springmvc.xmlparam-value>  
        init-param>  
        <load-on-startup>1load-on-startup>  
    servlet>  
    <servlet-mapping>  
        <servlet-name>dispatcherServletservlet-name>  
        <url-pattern>*.dourl-pattern>  
    servlet-mapping>  



      
    <filter>  
        <filter-name>characterEncodingFilterfilter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
        <init-param>  
            <param-name>encodingparam-name>  
            <param-value>UTF-8param-value>  
        init-param>  
    filter>  
    <filter-mapping>  
        <filter-name>characterEncodingFilterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping> 

web-app>

springmvc.xml配置

  
<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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd 
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

      
    <context:component-scan base-package="com.xnf.sas.*.*" />
    <context:component-scan base-package="com.xnf.sas.*.*.*" />

     
    <aop:aspectj-autoproxy proxy-target-class="true"/>

      
    <bean  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/">property>  
        <property name="suffix" value=".jsp">property>   
    bean>  
       

      
    <mvc:annotation-driven/> 
beans> 

applicationContext.xml配置

  
<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" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd 
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"  
    default-lazy-init="true">  

     
    <context:property-placeholder location="classpath:db.properties"/>
     
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
        <property name="user" value="${jdbc.user}">property>  
        <property name="password" value="${jdbc.password}">property>  
        <property name="driverClass" value="${jdbc.driverClass}">property>  
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}">property>  
        <property name="minPoolSize" value="${jdbc.minPoolSize}" />
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
        <property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
    bean>  

      
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
          
        <property name="dataSource" ref="dataSource">property>  
          
        
        <property name="namingStrategy">  
            <bean class="org.hibernate.cfg.ImprovedNamingStrategy">bean>  
        property>
         
        <property name="packagesToScan" value="com.xnf.sas.*.model">property>  
          
        <property name="hibernateProperties">  
            <props>  
              
                <prop key="hibernate.dialect">${hibernate.dialect}prop>  
                <prop key="hibernate.show_sql">${hibernate.show_sql}prop>  
                <prop key="hibernate.format_sql">${hibernate.format_sql}prop>  
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddlAuto}prop> 
            props>  
        property>  
    bean>  

      
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory">property>  
    bean>

    
    <aop:config>  
        <aop:advisor pointcut="execution(* com.xnf.sas.*.service.*.*(..))" advice-ref="txAdvice" />  
    aop:config>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="find*" read-only="true" propagation="REQUIRED" />
            <tx:method name="get*" read-only="true" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="*"  read-only="true" />
        tx:attributes>
    tx:advice>
beans> 

db.properties配置

jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/sas
jdbc.minPoolSize=15
jdbc.maxPoolSize=50
jdbc.initialPoolSize=15


hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddlAuto=update

log4j.properties日志文件配置(可省)

log4j.rootLogger=info,console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%-5p] %d %30c %m%n

log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern='-'yyyy-MM-dd
log4j.appender.file.File=../logs/springmvc-easyui-demo.log
log4j.appender.file.Append=true
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%-5p] %d %30c %m%n

下面我们项目结构和如何使用

SpringMVC4+Spring4+Hibernate4框架整合_第2张图片

实体类model

package com.xnf.sas.organization.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name="S_USER")
public class User{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="U_ID",nullable=false,unique=true)
    private long id;

    @Column(name="U_NAME")
    private String name;

    //以字段名'U_PASSWORD'映射到S_USER表中
    @Column(name="U_PASSWORD")
    private String password;

    //默认以字段名'sex'映射到S_USER表中
    private String sex;

    //不创建到数据库
    @Transient
    private String email;

    public User(String name,String password,String sex,String email){
        super();
        this.name=name;
        this.password=password;
        this.sex=sex;
        this.email=email;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

dao接口实现类

package com.xnf.sas.organization.dao.impl;


import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xnf.sas.organization.dao.UserDao;
import com.xnf.sas.organization.model.User;

@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    private SessionFactory sessionFactory;

    public void addUser(User user) {
        sessionFactory.getCurrentSession().save(user);
    }

    public User findUser(long id) {

        return (User)sessionFactory.getCurrentSession().get(User.class, id);
    }

    public void upadteUser(User user) {
        sessionFactory.getCurrentSession().update(user);
    }


}

service接口实现类

package com.xnf.sas.organization.service.impl;

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

import com.xnf.sas.organization.dao.UserDao;
import com.xnf.sas.organization.model.User;
import com.xnf.sas.organization.service.UserService;

@Service("userService2")
public class UserService2Impl implements UserService{

    @Autowired
    private UserDao userDao;

    public void addUser(User user) {
        System.out.println("**********userService2.addUser***********");
        userDao.addUser(user);  
    }

    public User findUser(long id) {
        return userDao.findUser(id);
    }

    public void upadteUser(User user) {
        userDao.upadteUser(user);       
    }


}
package com.xnf.sas.organization.service.impl;

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

import com.xnf.sas.organization.dao.UserDao;
import com.xnf.sas.organization.model.User;
import com.xnf.sas.organization.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    public void addUser(User user) {
        System.out.println("**********UserService.addUser***********");
        userDao.addUser(user);
    }

    public User findUser(long id) {
        return userDao.findUser(id);
    }

    public void upadteUser(User user) {
        userDao.upadteUser(user);       
    }


}

Controller类

package com.xnf.sas.organization.controller;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnf.sas.organization.model.User;
import com.xnf.sas.organization.service.UserService;


@Controller
@RequestMapping("/user")
public class UserController {

    //对UserService接口,当只有一个实现类继承接口时,可以使用@Autowired,接口实现类@Service注解即可。
    //多个的时候使用@Resource(name="userService2")来指定调那个子接口,接口实现类@Service("userService2")注解即可。
    //@Autowired
    //private UserService userService;

    @Resource(name="userService")
    private UserService userService;


    @Resource(name="userService2")
    private UserService userService2;

    //测试URL:http://localhost:8080/sas/user/addUser.do
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "addUser")
    public String addUser(){
        System.out.println("**********addUser***********");
        JSONObject obj = new JSONObject();
        User user = new User("user", "123456", "保密", "[email protected]");
        userService.addUser(user);
        User user2 = new User("user2", "123456", "保密", "[email protected]");
        userService2.addUser(user2);
        return obj.toString();
    }
}

//测试URL:http://localhost:8080/sas/user/addUser.do

数据库表

数据表

有需要的demo的可以点击下载SpringMVC4+Spring4+Hibernate4框架整合

你可能感兴趣的:(javaEE,Spring,hibernate,springMVC)