Spring+SpringMVC+Hibernate三大框架整合的SSH

1、三大框架简介

1.1、Spring

Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建。
简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。

1.2、SpringMVC

Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。
Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。
使用 Spring 可插入的 MVC 架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,如Struts1,Struts2等。

1.3、Hibernate

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系。
是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。
Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用。
最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。

2、三大框架整合步骤

2.1、准备工作

①安装JDK;
http://blog.csdn.net/qq_34197553/article/details/77504646
②安装Tomcat;
http://blog.csdn.net/qq_34197553/article/details/77597196
③安装Maven;
http://blog.csdn.net/qq_34197553/article/details/77600835
④安装一个IDE,如IntelliJ IDEA或者Eclipse等;

2.2、配置步骤

①创建一个Maven的webapp项目;
②在main目录下新建一个java的目录。如果使用的是IntelliJ IDEA,右键将java目录标记为Sources Root,并建立好相关包目录。如果使用的是Eclipse,则右键项目然后build path,config build path进行配置。建立如下图所示的基本架子;
Spring+SpringMVC+Hibernate三大框架整合的SSH_第1张图片

③配置pom.xml,导入架包;
pom.xml:

  4.0.0
  com.sshblog
  SSHBlog
  war
  1.0-SNAPSHOT
  SSHBlog Maven Webapp
  http://maven.apache.org

  

    
    1.8
    1.8
    2.5

    
    UTF-8
    UTF-8

    
    4.3.9.RELEASE

    
    4.3.11.Final

    
    5.1.43

    
    2.3.23

    
    1.7.7
    1.2.17

    
    0.9.1.2
  

  

    
    
      junit
      junit
      4.8.1
      test
    
    
      org.junit.jupiter
      junit-jupiter-api
      RELEASE
    

    
    
      org.springframework
      spring-test
      ${spring.version}
    
    
      org.springframework
      spring-web
      ${spring.version}
    
    
      org.springframework
      spring-core
      ${spring.version}
    
    
      org.springframework
      spring-tx
      ${spring.version}
    
    
      org.springframework
      spring-webmvc
      ${spring.version}
    
    
      org.springframework
      spring-aop
      ${spring.version}
    
    
      org.springframework
      spring-beans
      ${spring.version}
    
    
      org.springframework
      spring-context
      ${spring.version}
    
    
      org.springframework
      spring-expression
      ${spring.version}
    
    
      org.springframework
      spring-context-support
      ${spring.version}
    
    
      org.springframework
      spring-jdbc
      ${spring.version}
    
    
      org.springframework
      spring-orm
      ${spring.version}
    
    
      org.springframework
      spring-aspects
      ${spring.version}
    

    
    
      com.alibaba
      druid
      0.2.9
    

    
    
      com.alibaba
      fastjson
      1.1.18
    
    
      com.fasterxml.jackson.core
      jackson-core
      2.8.5
    
    
      com.fasterxml.jackson.core
      jackson-databind
      2.8.5
    
    
      org.codehaus.jackson
      jackson-mapper-asl
      1.9.13
    

    
    
      commons-collections
      commons-collections
      3.2.1
    

    
    
      commons-codec
      commons-codec
      1.9
    

    
    
      commons-io
      commons-io
      2.4
    
    
      commons-fileupload
      commons-fileupload
      1.3.1
    

    
    
      commons-net
      commons-net
      1.4.1
    

    
    
      commons-configuration
      commons-configuration
      1.9
    

    
    
      org.hibernate
      hibernate-core
      ${hibernate.version}
    

    
    
      javax.servlet
      jstl
      1.2
    

    
    
      c3p0
      c3p0
      ${c3p0.version}
    

    
    
      org.slf4j
      slf4j-api
      ${slf4j.version}
    
    
      org.slf4j
      slf4j-log4j12
      ${slf4j.version}
    
    
      log4j
      log4j
      ${log4j.version}
    
    
      commons-logging
      commons-logging
      1.2
    

    
    
      cglib
      cglib-nodep
      2.1_3
    
    
      aopalliance
      aopalliance
      1.0
    

    
    
      org.javassist
      javassist
      3.17.1-GA
    

    
    
      org.apache.commons
      commons-lang3
      3.4
    

    
    
      javax.transaction
      jta
      1.1
    

    
    
      mysql
      mysql-connector-java
      ${mysql-driver.version}
    

    
    
      dom4j
      dom4j
      1.6.1
    

    
    
      org.jsoup
      jsoup
      1.7.2
    

    
    
      antlr
      antlr
      2.7.7
    

    
    
      javax.servlet
      javax.servlet-api
      3.1.0
    

    
    
      org.projectlombok
      lombok
      1.16.6
    

    
    
      org.freemarker
      freemarker
      ${freemarker.version}
    

  
  
    SSHBlog

    
      
      
        org.mortbay.jetty
        maven-jetty-plugin
        6.1.19
        
          
            
              org.mortbay.jetty.Request.maxFormContentSize
              100000000
            
          
          10
          foo
          9999
          
          
            /
          
          
          automatic
          2
        
        
          
            start-jetty
            pre-integration-test
            
              run
            
            
              0
              true
            
          
          
            stop-jetty
            post-integration-test
            
              stop
            
          
        
      

      
      
        org.apache.maven.plugins
        maven-compiler-plugin
        
          ${maven.compiler.sourse}
          ${maven.compiler.target}
        
      

      
      
        org.apache.maven.plugins
        maven-resources-plugin
        ${maven.resources.version}
        
          
            copy-resources
            package
            
              copy-resources
            
            
              UTF-8
              ${project.build.directory}/lantooease/WEB-INF/
              
              
                
                  /src/main/resources
                  
                    *.xml
                    *.properties
                    *.conf
                  
                
              
            
          
        
      




    

  

④配置applicationContext.xml;
applicationContext.xml



    
    
    
    

    
    
        
            
                classpath:config.properties
            
        
    

    
    
    

    
    
    

    
    
        
        
            
                
                
                ${hibernate.hbm2ddl.auto}
                
                ${hibernate.dialect}
                
                ${hibernate.show_sql}
                
                ${hibernate.format_sql}
                
                ${hibernate.use_sql_comments}
                
                ${hibernate.generate_statistics}

                
                
                ${hibernate.c3p0.max_size}
                
                ${hibernate.c3p0.min_size}
                
                ${hibernate.c3p0.timeout}
                
                ${hibernate.c3p0.max_statements}
                
                ${hibernate.c3p0.idle_test_period}
                
                ${hibernate.c3p0.acquire_increment}
                
                ${hibernate.c3p0.validate}
            
        
        
        
    

    
    
    

    
    
        
        
        
        
            
                0
                UTF-8
                0.##########
                yyyy-MM-dd HH:mm:ss
                true
                ignore
            
        
    

    
    

其中,属性配置文件配置如下:
config.properties:
################### JDBC Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/SSHBlog?useUnicode=true&characterEncoding=utf8&useSSL=true&zeroDateTimeBehavior=convertToNull 
jdbc.username=root
jdbc.password=qwer1234

################### Hibernate Configuration ##########################
#Hibernate方言配置
hibernate.dialect=org.hibernate.dialect.MySQLDialect
#是否显示SQL语句
hibernate.show_sql=true
#是否自动更新表格
hibernate.hbm2ddl.auto=update
#Hibernate缓存统计策略配置
hibernate.generate_statistics=false
#是否使用格式化SQL语句
hibernate.format_sql=false
#在格式化的SQL语句的基础之上加强可读性
hibernate.use_sql_comments=false

################### 以下是Hibernate的c3p0配置 ##########################
#最大连接数
hibernate.c3p0.max_size=20
#最小连接数
hibernate.c3p0.min_size=5
#获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒
hibernate.c3p0.timeout=120
#最大的PreparedStatement的数量
hibernate.c3p0.max_statements=100
#每隔120秒检查连接池里的空闲连接 ,单位是秒
hibernate.c3p0.idle_test_period=120
#当连接池里面的连接用完的时候,C3P0一下获取的新的连接数
hibernate.c3p0.acquire_increment=2
每次都验证连接是否可用
hibernate.c3p0.validate=true
⑤配置spring-mvc.xml;
spring-mvc.xml:



    
    
    
    

    
    
    
        
            
                
            
        
        
            
        
    

    
    
        
        
            51200000
        
    
    
        
            
                error_fileupload
            
        
    

    
    
    
    
    
        
            /frontend/
        
    
    
        
        
        
    


⑥配置web.xml;
web.xml:


  sshblog

  
  
    contextConfigLocation
    classpath:applicationContext*.xml
  

  
  
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      UTF-8
    
  

  
  
    log4jConfigLocation
    classpath:log4j.properties
  
  
    log4jRefreshInteval
    600000
  
  
    org.springframework.web.util.Log4jConfigListener
  

  
  
    encodingFilter
    *.html
  
  
  
    encodingFilter
    *.json
  

  
  
    openSessionInView
    org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
  
  
    openSessionInView
    /*
  

  
  
    org.springframework.web.context.ContextLoaderListener
  

  
  
    org.springframework.web.util.IntrospectorCleanupListener
  

  
  
    dispatcher
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:spring-mvc.xml
    
    1
  
  
    dispatcher
    *.html
  
  
    dispatcher
    *.json
  

  
  
    30
  

  
  
    /index.html
    /index.jsp
  


  
    java.lang.Throwable
    /frontend/common/500.html
  
  
    500
    /frontend/common/500.html
  
  
    404
    /frontend/common/404.html
  


其中,日志属性文件配置如下:
log4j.properties:
log4j.rootCategory=info,stdout,R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) -%m%n
#日志文件存储路径配置
log4j.appender.R.file=./logFile.log
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c -%m%n

3、案例测试整合

3.1、Entity层

Entity层的实体类代码可以自动生成,生成方法参见: Hibernate实体类以及配置文件自动生成的方法
Contacts.java:
package com.sshblog.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "contacts")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer","handler","operations","roles","menus"})
public class Contacts {
    private int id;
    private String name;
    private String address;
    private String gender;
    private Date dob;
    private String email;
    private Long mobile;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

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

    @Basic
    @Column(name = "address")
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Basic
    @Column(name = "gender")
    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Basic
    @Column(name = "dob")
    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    @Basic
    @Column(name = "email")
    public String getEmail() {
        return email;
    }

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

    @Basic
    @Column(name = "mobile")
    public Long getMobile() {
        return mobile;
    }

    public void setMobile(Long mobile) {
        this.mobile = mobile;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Contacts contacts = (Contacts) o;

        if (id != contacts.id) return false;
        if (name != null ? !name.equals(contacts.name) : contacts.name != null) return false;
        if (address != null ? !address.equals(contacts.address) : contacts.address != null) return false;
        if (gender != null ? !gender.equals(contacts.gender) : contacts.gender != null) return false;
        if (dob != null ? !dob.equals(contacts.dob) : contacts.dob != null) return false;
        if (email != null ? !email.equals(contacts.email) : contacts.email != null) return false;
        if (mobile != null ? !mobile.equals(contacts.mobile) : contacts.mobile != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (address != null ? address.hashCode() : 0);
        result = 31 * result + (gender != null ? gender.hashCode() : 0);
        result = 31 * result + (dob != null ? dob.hashCode() : 0);
        result = 31 * result + (email != null ? email.hashCode() : 0);
        result = 31 * result + (mobile != null ? mobile.hashCode() : 0);
        return result;
    }
}
Contacts.hbm.xml:




    
        
        
        
        
        
        
        
    

3.2、DAO层

ContactsDAOI.java:
package com.sshblog.dao;

import com.sshblog.entity.Contacts;

import java.util.List;

public interface ContactsDAOI {
    public List findAllContacts();

    public void saveContact(Contacts contacts);

    public Contacts findById(int id);

    public void deleteContact(int id);

    public void updateContact(Contacts contacts);

    public List findByContactName(String name);
}
ContactsImpl.java:
package com.sshblog.dao.impl;

import com.sshblog.dao.ContactsDAOI;
import com.sshblog.entity.Contacts;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

@Repository
@Transactional
public class ContactsDAOImpl implements ContactsDAOI {
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List findAllContacts() {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contacts.class);
        return criteria.list();
    }

    @Override
    public void saveContact(Contacts contacts) {
        sessionFactory.getCurrentSession().save(contacts);
    }

    @Override
    public Contacts findById(int id) {
        Contacts contacts = (Contacts) sessionFactory.getCurrentSession().get(Contacts.class, id);
        return contacts;
    }

    @Override
    public void deleteContact(int id) {
        Contacts contacts = findById(id);
        sessionFactory.getCurrentSession().delete(contacts);
    }

    @Override
    public void updateContact(Contacts contacts) {
        sessionFactory.getCurrentSession().update(contacts);
    }

    @Override
    public List findByContactName(String name) {
        String hql = "from Contacts c where c.name like '%" + name + "%'";
        return sessionFactory.getCurrentSession().createQuery(hql).list();
    }
}

3.3、Service层

ContactsServiceI.java:
package com.sshblog.service;

import com.sshblog.entity.Contacts;

import java.util.List;

public interface ContactsServiceI {

    public List findAllUsers();

    public void saveContact(Contacts contacts);

    public void deleteContact(int id);

    public Contacts findById(int id);

    public void updateContact(Contacts contacts);

    public List findByUserName(String name);

}
ContactsServiceImpl.java:
package com.sshblog.service.impl;

import com.sshblog.dao.ContactsDAOI;
import com.sshblog.entity.Contacts;
import com.sshblog.service.ContactsServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service("contactsService")
@Transactional
public class ContactsServiceImpl implements ContactsServiceI {
    @Autowired
    private ContactsDAOI contactsDAOI;

    public void setContactsDAOI(ContactsDAOI contactsDAOI) {
        this.contactsDAOI = contactsDAOI;
    }

    @Override
    public List findAllUsers() {
        return this.contactsDAOI.findAllContacts();
    }

    @Override
    public void saveContact(Contacts contacts) {
        this.contactsDAOI.saveContact(contacts);
    }

    @Override
    public void deleteContact(int id) {
        this.contactsDAOI.deleteContact(id);
    }

    @Override
    public Contacts findById(int id) {
        return this.contactsDAOI.findById(id);
    }

    @Override
    public void updateContact(Contacts contacts) {
        this.contactsDAOI.updateContact(contacts);
    }

    @Override
    public List findByUserName(String name) {
        return this.contactsDAOI.findByContactName(name);
    }
}

3.4、Controller层

SSHBlogController.java:
package com.sshblog.controller;

import com.sshblog.entity.Contacts;
import com.sshblog.service.ContactsServiceI;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/")
public class SSHBlogController {
    @Autowired
    private ContactsServiceI contactsServiceI;

    public void setContactsServiceI(ContactsServiceI contactsServiceI) {
        this.contactsServiceI = contactsServiceI;
    }

    @RequestMapping("index")
    public ModelAndView indexPage(){
        ModelAndView mav = new ModelAndView("index");
        List contacts = this.contactsServiceI.findAllUsers();
        mav.addObject("contacts",contacts);
        return mav;
    }

    @RequestMapping(value = "save", method = RequestMethod.GET)
    public ModelAndView newContactPage(){
        ModelAndView mav = new ModelAndView("newContact");
        return mav;
    }

    @RequestMapping(value = "save", method = RequestMethod.POST)
    public String newContact(@RequestParam("dateOfb")String dob, Contacts contacts) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(dob);
        contacts.setDob(date);
        this.contactsServiceI.saveContact(contacts);
        return "redirect:index.html";
    }

    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String deleteContact(int id) {
        this.contactsServiceI.deleteContact(id);
        return "redirect:index.html";
    }

    @RequestMapping(value = "update", method = RequestMethod.GET)
    public ModelAndView editContactPage(int id){
        ModelAndView mav = new ModelAndView("editContact");
        Contacts contacts = this.contactsServiceI.findById(id);
        mav.addObject("editContact",contacts);
        return mav;
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String editContact(@RequestParam("dateOfb")Date date, Contacts contacts){
        contacts.setDob(date);
        this.contactsServiceI.updateContact(contacts);
        return "redirect:index.html";
    }

    @RequestMapping(value = "search", method = RequestMethod.POST)
    public ModelAndView searchByContactName(String name){
        ModelAndView mav = new ModelAndView("index");
        List contacts = this.contactsServiceI.findByUserName(name);
        mav.addObject("contacts",contacts);
        return mav;
    }

    @RequestMapping(value = "findAllUsers", method = RequestMethod.GET)
    @ResponseBody
    public List findAllUsers(){
        return this.contactsServiceI.findAllUsers();
    }
}

3.5、案例完成后的项目展开

如下图所示:
Spring+SpringMVC+Hibernate三大框架整合的SSH_第2张图片

4、运行测试

如果是使用的如上所示的jetty服务器,则以clean jetty:run命令运行项目;如果使用的是导入pom.xml中的tomcat服务器,则使用tomcat*:run来运行项目,其中*代表的是tomcat服务器的版本,tomcat6则*为6,tomcat7则*为7;如果是本地的tomcat服务器的话则在本地配置服务器运行项目即可。
运行后在浏览器上进行测试,如下图所示,则代表整合配置成功。
Spring+SpringMVC+Hibernate三大框架整合的SSH_第3张图片
测试能够访问到JSON,配置成功。

5、源码下载

本篇博客提供源码下载地址:
https://github.com/sam199510/SimpleSSHBlog

你可能感兴趣的:(Hibernate,Spring,SpringMVC,GitHub,SSH)