工程目录结构如下:

在这里插入图片描述

本工程只介绍SSH整合的基本流程,所以没有写接口

1. 导入jar包

<dependencies>
    <!--hibernate包-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>
    <!-- 添加mysql驱动依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.12</version>
    </dependency>
    <!--日志包-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.6.1</version>
    </dependency>
    <!--spring相关包-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <!--aop-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>
    <!--Servlet相关包-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>
<build>
    <finalName>ssh-test01</finalName>
    <!--要配置这个资源路径,否则xml文件找不到-->
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>

2. DAO和实体类

dao和实体类是hibernate相关的部分:
实体类Dept

package com.ssh.pojo;
public class Dept {
    private Integer id;
    private String name;
    //getter/setter方法略
}

映射文件Dept.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="com.ssh.pojo.Dept" table="DEPT">
        <id name="id" type="java.lang.Integer">
            <column name="ID" precision="10" scale="0"/>
            <generator class="identity"/>
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="20"/>
        </property>
    </class>
</hibernate-mapping>

实体类Employee

package com.ssh.pojo;

public class Employee {
    private Integer id;
    private String name;
    private Dept dept;
    //getter/setter方法略
}

映射文件:

<?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="com.ssh.pojo.Employee" table="EMPLOYEE">
        <id name="id" type="java.lang.Integer">
            <column name="ID" precision="10" scale="0"/>
            <generator class="identity"/>
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="20"/>
        </property>
        <!--多对一-->
        <many-to-one name="dept" class="com.ssh.pojo.Dept">
            <column name="DEPT_ID"/>
        </many-to-one>
    </class>
</hibernate-mapping>

EmployeeDAO

package com.ssh.dao;

import com.ssh.pojo.Employee;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

//HibernateDaoSupport是Spring提供的类,对Hibernate的Session进行了封装
public class EmployeeDAO extends HibernateDaoSupport {
    //添加
    public void addEmployee(Employee emp) {
        super.getHibernateTemplate().save(emp);
    }

    //条件查询
    public List<Employee> getEmpByCriteria(DetachedCriteria criteria) {
        return (List<Employee>)super.getHibernateTemplate().findByCriteria(criteria);
    }
}

DeptDAO

package com.ssh.dao;

import com.ssh.pojo.Dept;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

public class DeptDAO extends HibernateDaoSupport {

    public List<Dept> getDeptList() {
        return (List<Dept>) super.getHibernateTemplate().find("from Dept", null);
    }
}

3. Hibernate和Spring的整合

Hibernate和Spring整合的时候,Spring主要负责管理Hibernate的Session和事务
在spring-config.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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       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.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <!--spring管理数据源-->
    <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- 配置hibernate的SessionFactory -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- hibernate配置信息 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <!--也可以写单独的hibernate配置文件-->
        <!--<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>-->
        <!--扫描映射文件所在的包-->
        <!--<property name="mappingLocations" value="classpath:com/ssh/pojo/*.hbm.xml"/>-->
        <!--可以每个文件单独配置-->
        <property name="mappingResources">
            <list>
                <value>com/ssh/pojo/Employee.hbm.xml</value>
                <value>com/ssh/pojo/Dept.hbm.xml</value>
            </list>
        </property>
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!--事务增强-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为,匹配的是方法名 -->
            <tx:method name="add*" rollback-for="Exception"/>
            <tx:method name="delete*" rollback-for="Exception"/>
            <tx:method name="update*" rollback-for="Exception"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="do*" rollback-for="Exception"/>
        </tx:attributes>
    </tx:advice>
    <!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
    <aop:config>
        <aop:pointcut id="serviceMethod"
                      expression="execution(* com.ssh.service..*(..))"/>
        <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
    </aop:config>

    <bean id="employeeDAO" class="com.ssh.dao.EmployeeDAO">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <bean id="deptDAO" class="com.ssh.dao.DeptDAO">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
</beans>

数据库配置文件jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库?characterEncoding=utf-8
jdbc.username=用户名
jdbc.password=密码
日志文件log4j.properties
log4j.rootLogger=DEBUG, stdout, 

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

4. Service

EmployeeService

package com.ssh.service;

import com.ssh.dao.EmployeeDAO;
import com.ssh.pojo.Employee;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {
    @Autowired
    private EmployeeDAO employeeDAO;

    public void addEmployee(Employee emp) {
        employeeDAO.addEmployee(emp);
    }

    public List<Employee> getEmpByCriteria(DetachedCriteria criteria) {
        return employeeDAO.getEmpByCriteria(criteria);
    }
}

DeptService

package com.ssh.service;

import com.ssh.dao.DeptDAO;
import com.ssh.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeptService {
    @Autowired
    private DeptDAO deptDAO;

    public List<Dept> getDeptList(){
        return deptDAO.getDeptList();
    }
}

在spring-config.xml中配置对Service的扫描:

<context:component-scan base-package="com.ssh.service">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>

5. Controller

Controller就是SpringMVC的部分了:

package com.ssh.controller;

import com.ssh.pojo.Dept;
import com.ssh.pojo.Employee;
import com.ssh.service.DeptService;
import com.ssh.service.EmployeeService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmpController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DeptService deptService;

    @RequestMapping("/list.html")
    public String list(Employee employee, Model model) {
        //封装查询条件
        DetachedCriteria criteria=DetachedCriteria.forClass(Employee.class);
        if(employee.getName()!=null&&employee.getName().trim().length()>0){
            criteria.add(Restrictions.like("name","%"+employee.getName()+"%"));
        }
        model.addAttribute("employeeList", employeeService.getEmpByCriteria(criteria));
        return "/emp_list.jsp";
    }

    //去添加员工的页面
    @RequestMapping("/go_add.html")
    public ModelAndView goAdd() {
        List<Dept> deptList = deptService.getDeptList();
        return new ModelAndView("/emp_add.jsp", "deptList", deptList);
    }

    @RequestMapping("/add.html")
    public String add(Employee employee) {
        employeeService.addEmployee(employee);
        //添加成功后跳转到列表页
        return "redirect:/emp/list.html";
    }

}

SpringMVC-servlet.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
    <!-- 启动注解,注册服务-->
    <mvc:annotation-driven/>

    <!-- 启动自动扫描 -->
    <context:component-scan base-package="com.ssh.controller">
        <!-- 制定扫包规则 ,只扫描使用@Controller注解的JAVA类 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
         version="3.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-config.xml</param-value>
    </context-param>
    <!--配置listener,在启动Web容器的时候加载Spring的配置-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
<!--处理中文乱码-->
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
    <!--处理hibernate懒加载问题-->
    <filter>
        <filter-name>openSessionInView</filter-name>
        <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>openSessionInView</filter-name>
        <url-pattern>*.html</url-pattern>
    </filter-mapping>
    <!--配置DispatcherServlet -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

6. 页面

emp_add.jsp

<form action="/emp/add.html" method="post">
    员工姓名:<input type="text" name="name"/><br/>
    部门:<select name="dept.id">
    <c:forEach items="${deptList}" var="dept">
        <option value="${dept.id}">${dept.name}</option>
    </c:forEach>
</select><br/>
    <input type="submit" value="提交"/>
</form>

运行结果:

在这里插入图片描述

emp_list.jsp

<form action="/emp/list.html" method="post">
    员工姓名:<input type="text" name="name"/>
    <input type="submit" value="搜索"/>
</form>
<table>
    <tr>
        <td>id</td>
        <td>姓名</td>
        <td>部门</td>
    </tr>
    <c:forEach items="${employeeList}" var="emp">
        <tr>
            <td>${emp.id}</td>
            <td>${emp.name}</td>
            <td>${emp.dept.name}</td>
        </tr>
    </c:forEach>
</table>

运行结果:

在这里插入图片描述

更多推荐