SpringFramework+Mybatis项目整合
整合项目的版本统一
- IDE Idea 2020.1.1
- JDK 1.8.131
- MySQL数据库 5.5.17 com.mysql.jdbc.Driver
- Tomcat 7.0.70
- Maven 3.6.1
- 浏览器:Google
- SpringFramework 4.3.3.RELEASE
- 项目结构截图
- 配置文件编写
- Maven项目的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.neutech.springframework</groupId> <artifactId>sd_springframework_mybatis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging>
<name>sd_springframework_mybatis Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url>
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <!-- 统一设定SpringFramework的所有组件版本 --> <spring.version>4.3.3.RELEASE</spring.version> </properties>
<dependencies> <!-- MySQL的驱动 --> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- 阿里巴巴的Druid数据源 --> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.16</version> </dependency> <!-- ServletAPI --> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- Mybatis框架 --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- Spring相关依赖 core、aop、beans、springweb... --> <!-- AOP相关组件 --> <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance --> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.10</version> </dependency>
<!-- 事务管理器 Transactional--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!-- JUnit单元测试使用 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- SpringMVC相关依赖 --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- 日志文件输出 --> <!-- 小辣椒lombok --> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> <scope>provided</scope> </dependency> <!-- 文件上传组件 --> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <!-- JSTL标签库 --> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 处理JSON字符串--> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency>
<!-- SpringFramework整合必须的依赖包(新) --> <!-- Spring提供的获取SqlSession对象的组件 --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency>
<!-- Spring整合Mybatis的插件 --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> </dependencies>
<build> <finalName>sd_springframework_mybatis</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project> |
- tomcat启动时加载web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app> <display-name>Archetype Created Web Application</display-name> <!-- 配置加载Spring的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application.xml</param-value> </context-param> <!-- 解决中文乱码问题 --> <filter> <filter-name>encoding</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> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<!-- 由全局监听器加载Spring的配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 初始化参数 替代在WEB-INF/XX-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> |
- 加载Spring的主配置文件application.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: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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 添加注解 --> <context:component-scan base-package="com.neutech.springframework" /> <!-- 使用aop中的动态代理 --> <aop:aspectj-autoproxy /> <!-- 配置数据源 --> <!-- 使用.properties文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <!-- <property name="location" value="classpath:db.properties" /> --> <property name="locations" > <list> <value>classpath:db.properties</value> </list> </property> </bean> <!-- 阿里的Druid数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="10" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="120000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> </bean> <!-- 通过Spring加载Mybatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!--<property name="configLocation" value="classpath:mybatis-conf.xml" />--> <!-- 取别名 --> <property name="typeAliasesPackage" value="com.neutech.springframework.entity"/> <!-- 注册接口文件 --> <property name="mapperLocations" value="classpath:*Mapper.xml"/> </bean> <!-- 声明式事务配置 --> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置事务通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 配置哪些方法使用何种事务,配置事务的传播特性 --> <tx:method name="add" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="delete" propagation="REQUIRED" /> <tx:method name="update" propagation="REQUIRED" /> <!-- <tx:method name="myMethod" read-only="true" /> --> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.neutech.springframework.service.impl.*.*(..))" id="pointcut" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" /> </aop:config> <!-- 事务注解 --> <tx:annotation-driven/> </beans> |
- 加载SpringMVC的主配置文件mvc.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:p="http://www.springframework.org/schema/p" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置注解扫描 --> <context:component-scan base-package="com.neutech.springframework.controller" /> <!--<context:annotation-config/>--> <!-- 文件上传的解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> <!-- 配置Json转换器 --> <bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=utf-8</value> </list> </property> </bean> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="stringConverter"/> <ref bean="jsonConverter"/> </list> </property> </bean> <!-- mvc的注解驱动 --> <mvc:annotation-driven/> <!-- 放行在webapp下的所有静态资源文件 --> <mvc:default-servlet-handler /> </beans> |
- 加载Mybatis的主配置文件mybatis-conf.xml。(由于使用Spring整合Mybatis,所以此文件文件不需要配置)
<?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> <!--<!– 取别名 –> <typeAliases> <package name="com.neutech.springframework.entity" /> </typeAliases>--> <!-- 加载XXMapper.xml --> <!--<mappers> <package name="com.neutech.springframework.mapper"/> </mappers>--> </configuration> |
- 加载注册的XXMapper.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.neutech.springframework.mapper.IAdminMapper"> <sql id="baseSQL"> id,name,pwd </sql> <select id="selectAll" resultMap="findAll"> select <include refid="baseSQL"/> from t_admin </select> <resultMap id="findAll" type="Admin"> <id property="id" column="id" javaType="java.lang.Integer"/> <result property="name" column="name" javaType="java.lang.String"/> <result property="password" column="pwd" javaType="java.lang.String"/> </resultMap> </mapper> |
- 数据源的配置db.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/sd_mybatis?characterEncoding=utf8 jdbc.username=root jdbc.password=root |
- 代码编写
- 数据表的创建 前缀:“t_”
/* Navicat Premium Data Transfer
Source Server : wp_MySQL Source Server Type : MySQL Source Server Version : 50534 Source Host : localhost:3306 Source Schema : sd_mybatis
Target Server Type : MySQL Target Server Version : 50534 File Encoding : 65001
Date: 12/04/2021 10:35:42 */
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0;
-- ---------------------------- -- Table structure for t_admin -- ---------------------------- DROP TABLE IF EXISTS `t_admin`; CREATE TABLE `t_admin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `pwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 34 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ---------------------------- -- Records of t_admin -- ---------------------------- INSERT INTO `t_admin` VALUES (1, '管理员1', '123456'); INSERT INTO `t_admin` VALUES (4, '黑猫警长', '123456'); INSERT INTO `t_admin` VALUES (6, '叶伟见', '000'); INSERT INTO `t_admin` VALUES (7, '穆金羽', '111222333'); INSERT INTO `t_admin` VALUES (8, '凡尘', '456'); INSERT INTO `t_admin` VALUES (9, '姚佳东', 'asdjfkalsd'); INSERT INTO `t_admin` VALUES (11, 'Jerry', '000000'); INSERT INTO `t_admin` VALUES (25, 'admin', 'admin'); INSERT INTO `t_admin` VALUES (26, 'admin2', '123'); INSERT INTO `t_admin` VALUES (29, '李磊', '9999'); INSERT INTO `t_admin` VALUES (30, '李磊', '9999'); INSERT INTO `t_admin` VALUES (31, '李磊', '9999'); INSERT INTO `t_admin` VALUES (32, '李磊', '9999'); INSERT INTO `t_admin` VALUES (33, '李磊', '9999'); |
- 根据数据表生成实体类entity Admin.java
package com.neutech.springframework.entity;
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;
import java.io.Serializable;
/** * @author Neuedu-远哥 * @version 1.0 * @date 2021/4/12 10:01 */ @Data @AllArgsConstructor @NoArgsConstructor public class Admin implements Serializable { private Integer id; private String name; private String password; } |
- 持久层:创建entity对应实体类的接口IAdminMapper.java
package com.neutech.springframework.mapper;
import com.neutech.springframework.entity.Admin;
import java.util.List;
/** * @author Neuedu-远哥 * @version 1.0 * @date 2021/4/12 10:02 */ public interface IAdminMapper { List<Admin> selectAll(); } |
- IAdminMapper接口的实现类AdminMapperImpl.java
package com.neutech.springframework.mapper.impl;
import com.neutech.springframework.entity.Admin; import com.neutech.springframework.mapper.IAdminMapper; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;
import java.util.List;
/** * SqlSessionDaoSupport: <br> * Spring整合Mybatis用到的父类, * 作用:代替原来的Mybatis创建SQLSession对象 * @author Neuedu-远哥 * @version 1.0 * @date 2021/4/12 10:07 */ @Repository public class AdminMapperImpl extends SqlSessionDaoSupport implements IAdminMapper { @Autowired @Override public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { super.setSqlSessionFactory(sqlSessionFactory); }
@Override public List<Admin> selectAll() { return getSqlSession().getMapper(IAdminMapper.class).selectAll(); } } |
- IAdminMapper接口的实现AdminMapper.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.neutech.springframework.mapper.IAdminMapper"> <sql id="baseSQL"> id,name,pwd </sql> <select id="selectAll" resultMap="findAll"> select <include refid="baseSQL"/> from t_admin </select> <resultMap id="findAll" type="Admin"> <id property="id" column="id" javaType="java.lang.Integer"/> <result property="name" column="name" javaType="java.lang.String"/> <result property="password" column="pwd" javaType="java.lang.String"/> </resultMap> </mapper> |
- Service层:创建IAdminService接口
package com.neutech.springframework.service;
import com.neutech.springframework.entity.Admin;
import java.util.List;
/** * @author Neuedu-远哥 * @version 1.0 * @date 2021/4/12 10:05 */ public interface IAdminService { List<Admin> selectAll(); } |
- IAdminService的实现类AdminServiceImpl.java
package com.neutech.springframework.service.impl;
import com.neutech.springframework.entity.Admin; import com.neutech.springframework.mapper.IAdminMapper; import com.neutech.springframework.service.IAdminService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
import java.util.List;
/** * @author Neuedu-远哥 * @version 1.0 * @date 2021/4/12 10:06 */ @Service public class AdminServiceImpl implements IAdminService {
private IAdminMapper mapper; @Autowired public void setMapper(IAdminMapper mapper) { this.mapper = mapper; }
@Override public List<Admin> selectAll() { System.out.println("业务逻辑处理层。。。"); return mapper.selectAll(); } } |
- 控制层:XXController.java
package com.neutech.springframework.controller;
import com.neutech.springframework.entity.Admin; import com.neutech.springframework.service.IAdminService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/** * @author Neuedu-远哥 * @version 1.0 * @date 2021/4/12 10:11 */ @Controller @RequestMapping("/admin") public class AdminController {
private IAdminService service; @Autowired public void setService(IAdminService service) { this.service = service; }
@RequestMapping("/admin_list") public String findAll(ModelMap map){ List<Admin> admins = service.selectAll(); map.addAttribute("admins",admins); return "admins.jsp"; }
@ResponseBody @RequestMapping("/admins_list_ajax") public List<Admin> selectAll(){ return service.selectAll(); } } |
- 通过转发和重定向生成对应的页面 admins.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" isELIgnored="false" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>管理员列表</title> <style rel="stylesheet"> h2 { text-align: center; } </style> </head> <body> <h2>管理员列表</h2> <table border="1" align="center" cellpadding="0" cellspacing="0" width="70%"> <tr> <th>ID</th><th>管理员名</th><th>管理员密码</th> </tr> <c:forEach items="${admins}" var="admin"> <tr> <td>${admin.id}</td><td>${admin.name}</td><td>${admin.password}</td> </tr> </c:forEach> </table> </body> </html> |
- 测试:
访问:http://localhost:8080/ssm/admin/admin_list