SSM高级整合_Maven方式

简介: 使用Maven方式整合SSM, 用到的框架: Spring5.2.5, MyBatis3.5.5, C3P0 0.9.5.2, Jdbc8.1.8, Jstl1.2, Junit4+Spring5.2.5Test单元测试, log4j1.2.7(mybatis项目配置log4j打印sql语句)

 

一, 结构目录

 

 

 

 

 1,pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zdx.ssm</groupId>
    <artifactId>ssm_crud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <!-- 增加依赖的Jar -->
    <dependencies>
        <!-- spring, spring mvc --> 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

        <!-- spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

        <!-- spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

        <!-- Mybatis --> 
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <!-- mybatis-spring 整合包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>

        <!-- c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!-- mysql8 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

        <!-- Jstl --> 
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

        <!-- Junit4 --> 
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
 
        <!-- Spring test 单元测试 --> 
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

        <!-- mybatis项目配置log4j打印sql语句 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency> 
        
    </dependencies>
</project>

2, web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    id="WebApp_ID" version="4.0">
    <display-name>ssm_crud</display-name>

    <!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- 在servlet初始化之前引导根web应用程序上下文 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 这个Spring Web应用程序的前端控制器,负责处理所有应用程序请求 -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- 将所有请求映射到DispatcherServlet进行处理 -->
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <!-- 字符集过滤器 -->
    <filter>
       <filter-name>dharacterEncodingFilter</filter-name>
       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
       <init-param>
           <param-name>forceRequestEncoding</param-name>
           <param-value>true</param-value>
       </init-param>
       <init-param>
           <param-name>forceResponseEncoding</param-name>
           <param-value>true</param-value>
       </init-param>
    </filter>
    <filter-mapping>
       <filter-name>dharacterEncodingFilter</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 使用Rest风格的URL -->
    <filter>
       <filter-name>hiddenHttpMethodFilter</filter-name>
       <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
       <filter-name>hiddenHttpMethodFilter</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

3, springMVC.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        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">

    <!-- 配置自动扫描的包, 只扫描@Controller注解的包 -->
    <context:component-scan base-package="com.zdx.ssm" use-default-filters="false">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="/WEB-INF/pages/"></property>
       <property name="suffix" value=".jsp"></property>
    </bean>
    
    <!-- 两个标准配置 -->
    <!-- 将SpringMVC不能处理的静态资源交能Tomcat Servlet处理 -->
    <mvc:default-servlet-handler/>
    <!-- 能支持SpringMVC更高级的一些功能,如JSR303校验,快捷的Ajax,映射动态的请求 -->    
    <mvc:annotation-driven/> 
</beans>

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

    <!-- 管理所有业务Bean,数据源,事务 -->
    <!-- 配置扫描的包,除@Controller注解的之外的包 -->
    <context:component-scan base-package="com.zdx.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 引入外部文件 -->
    <context:property-placeholder location="classpath:dbconfig.properties" />
    <!-- 数据源 连接池 -->
    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- 配置与MyBatis整合 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="pooledDataSource" />
        <!-- 指定Mybatis全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 指定mybatis mapper文件位置 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!-- 配置扫描器,将mybatis接口的实现类加入到IOC容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描所有Dao接口的实现 -->
        <property name="basePackage" value="com.zdx.ssm.dao" />
    </bean>

    <!-- 事务控制配置 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源 -->
        <property name="dataSource" ref="pooledDataSource" />
    </bean>

    <!-- 开启配置的事务注解 -->
    <aop:config>
        <!-- 切入点表达式 -->
        <aop:pointcut expression="execution(* com.zdx.ssm.service..*(..))" id="txPoint" />
        <!-- 配置事务增强 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint" />
    </aop:config>

    <!-- 配置事务增加,事物如何切入 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 所有的方法都是事务方法 -->
            <tx:method name="*" />
            <!-- 以get开头的所有方法 务 -->
            <tx:method name="get*" read-only="true" />
        </tx:attributes>
    </tx:advice> 
</beans>

5, mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
  <configuration>
    <settings>
        <!-- 开启驼峰命名自动映射 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- mybatis项目配置log4j打印sql语句 -->
        <setting name="logImpl" value="LOG4J"/>
        <!--显式的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题 -->
        <setting name="cacheEnabled" value="true" />
        <setting name="lazyLoadingEnabled" value="true" />
        <setting name="aggressiveLazyLoading" value="false" />
    </settings>
    
    <!-- 类别名 -->
    <typeAliases>
        <package name="com.zdx.ssm.bean"/>
    </typeAliases>
  
  </configuration>

6, dbcpconfig.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_crud?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=123456

7, log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
   <param name="Encoding" value="UTF-8" />
   <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
   </layout>
 </appender>
 <logger name="java.sql">
   <level value="debug" />
 </logger>
 <logger name="org.apache.ibatis">
   <level value="info" />
 </logger>
 <root>
   <level value="debug" />
   <appender-ref ref="STDOUT" />
 </root>
</log4j:configuration>

 

 

 

二, 数据库结构

 

 

 

 

三, Bean

Employee

public class Employee {
    private Integer id;
    private String userName;
    private String email;
    private String gender;
    private Department department;
}

 

Department

public class Department {
    private Integer id;
    private String name;
    private List<Employee> employees;
}

四,Dao

EmployeeMapper
public interface EmployeeMapper {

    List<Employee> getEmployees();

    List<Employee> getEmployeesWithDepatment();

    List<Employee> getEmployeesByDepartmentId(Integer departmentId);

    Employee getEmployeeById(Integer id);

    int add(Employee employee);

}

DepartmentMapper

public interface DepartmentMapper {

    List<Department> getDepartments();

    Department getDepartmentById(Integer id);

    Department getDepartmentsWithEmployee(Integer id);
}

五, 映射文件

EployeeMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zdx.ssm.dao.EmployeeMapper">

    <!-- 查询所有员工 -->
    <select id="getEmployees" resultType="com.zdx.ssm.bean.Employee">
        SELECT * FROM employee
    </select>
    
    <!-- 根据部门Id查询所有员工 -->
    <select id="getEmployeesByDepartmentId" resultType="employee" >
       select * from employee where department_id = #{departmentId}
    </select>

    <!-- 增加员工 -->
    <insert id="add" parameterType="employee">
        INSERT INTO employee (user_name, email, gender) VALUES (#{userName}, #{email}, #{gender})
    </insert>
     
    <!-- 带部门信息查询 -->
    <!-- 一,级联属性封装结果集 -->
    <!-- <resultMap type="employee" id="employeeWithDepartment">
        <id column="id" property="id" />
        <result column="user_name" property="userName" />
        <result column="email" property="email" />
        <result column="gender" property="gender" />
        <result column="id" property="department.id" />
        <result column="name" property="department.name" />
    </resultMap>
    <select id="getEmployeesWithDepatment" resultMap="employeeWithDepartment">
        SELECT e.id, e.user_name, e.email, e.gender, d.id did, d.name FROM employee e, department d WHERE e.`department_id`=d.`id`
    </select> -->

    <!-- 二,使用association定义关联的单个对象的封装规则 -->
    <!-- <resultMap type="employee" id="employeeWithDepartment">
        <id column="id" property="id" />
        <result column="user_name" property="userName" />
        <result column="email" property="email" />
        <result column="gender" property="gender" />
        <association property="department" javaType="department">
            <id column="id" property="id" />
            <result column="name" property="name" />
        </association>
    </resultMap>
    <select id="getEmployeesWithDepatment" resultMap="employeeWithDepartment"> 
       SELECT e.id, e.user_name, e.email, e.gender, d.id did, d.name FROM employee e, department d 
       WHERE e.`department_id`=d.`id`
    </select> -->

    <!-- 三,使用association 分步查询:可以使用延迟加载 -->
    <resultMap type="employee" id="employeeWithDepartment">
        <!-- property="department" 对应Employee Bean中属性 private Department department; -->
        <!-- column="id" 传递的参数 -->
        <association property="department" 
          select="com.zdx.ssm.dao.DepartmentMapper.getDepartmentById" column="id" fetchType="lazy" />
    </resultMap>
    <select id="getEmployeesWithDepatment" resultMap="employeeWithDepartment">
        SELECT * FROM employee
    </select>

</mapper>

DepartmentMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zdx.ssm.dao.DepartmentMapper"> 
    <!-- 查询所有部门 -->
    <select id="getDepartments" resultType="com.zdx.ssm.bean.Department">
        SELECT * FROM department
    </select>
 
    <!-- 根据Id查询部门 -->
    <select id="getDepartmentById" resultType="com.zdx.ssm.bean.Department">
        SELECT * FROM department WHERE id = #{id}
    </select>
    
    <!-- 带员工列表的查询 根据Id查询部门和员工 -->
    <!-- 一,嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则 -->
    <!-- ofType:指定集合里面元素的类型 -->
    <!-- <resultMap type="department" id="departmentWithEmployee">
        <id column="id" property="id"/>
        <result column="name" property="name"/> 
        <collection property="employees" ofType="employee">
            <id column="id" property="id"/>
            <result column="user_name" property="userName"/>
            <result column="email" property="email"/>
            <result column="gender" property="gender"/>
        </collection>
    </resultMap>
    <select id="getDepartmentsWithEmployee" resultMap="departmentWithEmployee">
        SELECT d.id, d.name, e.user_name, e.email, e.gender FROM department d 
            LEFT JOIN employee e ON d.id = e.department_id WHERE d.id = #{id}
    </select> -->
    
    <!-- 二,分步式查询: 可以使用延迟加载 -->
    <resultMap type="department" id="departmentWithEmployee"> 
        <!-- property="employees" 对应Department Bean中属性  private List<Employee> employees; -->
        <!-- column="id" 传递的参数,如果有多个写法column="{key1=column1,key2=column2}" -->
        <collection property="employees" 
            select="com.zdx.ssm.dao.EmployeeMapper.getEmployeesByDepartmentId" column="id" fetchType="lazy">
        </collection>
    </resultMap>
    <select id="getDepartmentsWithEmployee" resultMap="departmentWithEmployee">
        SELECT * FROM department where id = #{id}
    </select> 
</mapper>

 

六, Spring Test + Junint4 测试

package com.zdx.ssm.test;

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.zdx.ssm.bean.Department;
import com.zdx.ssm.bean.Employee;
import com.zdx.ssm.dao.DepartmentMapper;
import com.zdx.ssm.dao.EmployeeMapper;

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

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;

    @Test
    public void testgetDepartmentById() {
        Department department = departmentMapper.getDepartmentById(1);
        System.out.println(department);
    }

    @Test
    public void testGetDepartmentsWithEmployee() {
        Department department = departmentMapper.getDepartmentsWithEmployee(1);
        System.out.println(department + ", employees==>" + department.getEmployees());
    }

    // =========================================================
    @Test
    public void testCRUD() {
        Employee employee = new Employee("zhangq", "zhangq@qq.com", "M");
        int i = employeeMapper.add(employee);
        System.out.println("add=>" + i);
    }

    @Test
    public void testGetEmployees() {
        List<Employee> employees = employeeMapper.getEmployees();
        System.out.println(employees);
    }

    @Test
    public void testGetEmployeesByDepartmentId() {
        List<Employee> employees = employeeMapper.getEmployeesByDepartmentId(2);
        for (int i = 0; i < employees.size(); i++) {
            System.out.println(employees.get(i));
        }
    }

    @Test
    public void testGetEmployeesWithDepartment() {
        List<Employee> employees = employeeMapper.getEmployeesWithDepatment();
        for (int i = 0; i < employees.size(); i++) {
            System.out.println(employees.get(i).getEmail() + "-" + employees.get(i).getDepartment().getName());
        }
    }

}

 

posted @ 2020-12-13 22:29  弓长大仙  阅读(195)  评论(0)    收藏  举报