参考网上的教程,搭建一个可以使用的 Spring、SpringMVC、Mybatis 框架
一、IDEA 新建项目一个maven 项目
项目模板选择如下:
image.png
项目结构如下:
src
-> main
下新建一个Directory,命名为java
,右键标记为Sources Root
二、引入包
编辑pom.xml
为如下格式,引入所需包和配置
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<name>SSMDemo</name>
<groupId>com.wishuok</groupId>
<artifactId>SSMDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<!--版本信息共有提取版本号,便于后期项目版本提升,查找麻烦,这里的标签名称随意命名-->
<properties>
<spring.version>5.0.4.RELEASE</spring.version>
<aspectJ.version>1.8.13</aspectJ.version>
<mybatis.version>3.4.6</mybatis.version>
<mybatis.spring.version>1.3.2</mybatis.spring.version>
<oracle.version>11.2.0.1.0</oracle.version>
<log4j.version>1.2.17</log4j.version>
<c3p0.version>0.9.5.4</c3p0.version>
<servlet.version>3.1.0</servlet.version>
<jstl.version>1.2.5</jstl.version>
<jackson.version>2.9.8</jackson.version>
<commons.lang3.version>3.7</commons.lang3.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.7</version>
<configuration>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8888</port>
<maxIdleTime>30000</maxIdleTime>
</connector>
</connectors>
<webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
<contextPath>/</contextPath>
</configuration>
</plugin>
<!-- mybatis-generator自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<verbose>true</verbose><!-- 打印创建info信息 -->
<overwrite>true</overwrite><!-- 重写生成的代码,除了mapper.xml文件是在最后追加sql语句 -->
</configuration>
</plugin>
<!--Maven编译插件,指定编译的jdk版本,和字符编码-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!--dependency>
<groupId>com.wishuok</groupId>
<artifactId>[the artifact id of the block to be mounted]</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency-->
<!--spring 基础包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring 事务包 jdbc,tx-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring web mvc 模块-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring整合的测试包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--AespectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectJ.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectJ.version}</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mybatis-spring整合包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!--c3p0数据源-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<!--日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<!--jstl-->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-jstlel</artifactId>
<version>${jstl.version}</version>
</dependency>
<!--jackson数据转换包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<!--cocommons-lang3 帮助包-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
</dependencies>
</project>
三、mybatis-generator
1、resources
目录下新增 c3p0.properties
文件
配置mysql数据库和数据库连接池
jdbc.classPath = Z:\\CodingUse\\Softwares\\apache-maven-3.6.0\\repository\\mysql\\mysql-connector-java\\8.0.16\\mysql-connector-java-8.0.16.jar
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.109.128:3306/test?serverTimezone=UTC
jdbc.username=mysqluser
jdbc.password=root
c3p0.maxPoolSize = 500
c3p0.minPoolSize = 5
c3p0.acquireIncrement = 10
c3p0.maxIdleTime = 60000
c3p0.checkoutTimeout = 60000
2、resources
目录下新增 generatorConfig.xml
文件
配置mybatis-generator
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 引入外部数据库配置文件:通过el表达式进行读取 -->
<properties resource="c3p0.properties"/>
<!-- 指定数据连接驱动jar地址 !!!!!这个是必须的!!!-->
<classPathEntry location="${jdbc.classPath}" />
<!-- 一个数据库一个context -->
<!-- targetRuntime之后加上simple可以生成简单版 MyBatis3 复杂版-->
<context id="infoGuardian" targetRuntime="MyBatis3">
<!-- 生成的pojo,将implements Serializable -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
<!-- 注释 -->
<commentGenerator >
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<!--<property name="suppressDate" value="true" /> <!– 是否生成注释代时间戳–>-->
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}"
userId="${jdbc.username}"
password="${jdbc.password}" >
<!--MySQL 不支持 schema 或者 catalog 所以需要添加这个-->
<!--参考 : http://www.mybatis.org/generator/usage/mysql.html-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="com.wishuok.pojo" targetProject="src/main/java" >
<!-- 是否在当前路径下新加一层schema -->
<property name="enableSubPackages" value="false"/>
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="mybatis/mappers" targetProject="src/main/resources" >
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成mapxml对应client,也就是接口dao -->
<javaClientGenerator targetPackage="com.wishuok.mapper" targetProject="src/main/java" type="XMLMAPPER" >
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!--要生成的数据库表-->
<table tableName="user" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
<!--字段名称使用骆驼命名方式:dept_no 变为deptNo-->
<property name="useActualColumnNames" value="false" />
</table>
<table tableName="role" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
<property name="useActualColumnNames" value="true" />
</table>
</context>
</generatorConfiguration>
3、目录结构
image.png4、生成实体和mapper
image.png双击图中,或命令行运行
mvn mybatis-generator:generate
会根据
generator-config
的配置生成Entity和Mapper,以及xml文件到指定的包和目录自动生成的项目可以参考这里
四、Spring 和 mybatis 配置
1、新增 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="autoMappingBehavior" value="FULL"/>
<!--开启数据库字段和实体字段的骆驼命名映射 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--指定mybatis项目使用log4j配置文件完成日志输出,避免整合spring框架后不能打印sql语句-->
<setting name="logImpl" value="LOG4J" />
</settings>
<typeAliases>
<!--别名开启,在sql映射中不用再写实体类的全类名-->
<package name="com.wishuok.pojo" />
</typeAliases>
</configuration>
image.png
2、新增 spring-mybatis.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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--加载c3p0.properties-->
<context:property-placeholder location="classpath:c3p0.properties" />
<!--配置数据源-->
<bean id="dataSource" 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}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
<property name="acquireIncrement" value="${c3p0.acquireIncrement}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
</bean>
<!--配置SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
<property name="mapperLocations" value="classpath:mybatis/mappers/*Mapper.xml"/>
</bean>
<!--交给Mapper 完成自动扫描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.wishuok.mapper" />
</bean>
<!--配置事务管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--使用注解完成事务管理,注册-->
<tx:annotation-driven />
<!--把DAO交给Service-->
<context:component-scan base-package="com.wishuok.service.impl" />
</beans>
image.png
3、新增spring-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: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">
<!--设置Controller控制器的扫描地址-->
<context:component-scan base-package="com.wishuok.controller" />
<!-- 配置springmvc返回数据的数据格式,注意必须放在<mvc:annotation-driven>之前 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
<!--注解驱动,很多配置都需要它(比如上传下载,类型转换器...),一般都会添加该配置-->
<mvc:annotation-driven />
<!--
静态资源映射,应为WEB-INF是一个安全目录,不能使用get访问,而外部的js,css都是属性get访问,所有需要映射,不然无法读取
location:项目真实路径 mapping:映射路径
-->
<mvc:resources mapping="/resource/**" location="/WEB-INF/resource" />
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
4、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--字符编码过滤器-->
<filter>
<filter-name>EncodingFilter</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>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--加载Spring IOC容器-->
<context-param>
<!--配置SpringIOC容器所在的地址,如果不配,则默认应该放在WEB-INF目录下,且该文件必须已 【-servlet.xml】结尾-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-mybatis.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--加载spring mvc 模块,SpringMVC中央管理器-->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--404错误页面配置-->
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/pages/404.jsp</location>
</error-page>
</web-app>
若 maven 模板的web.xml太旧,可按照如下生成一个基于新版的config
image.png
五、编写 Service
和 controller
1、接口
package com.wishuok.service;
import com.wishuok.pojo.Role;
public interface IRoleService {
Role findRoleById(String id);
}
2、实现
package com.wishuok.service.impl;
import com.wishuok.mapper.RoleMapper;
import com.wishuok.pojo.Role;
import com.wishuok.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//添加Service注解,让Spring进行实例化管理,并给该实例化对象取一个名字,后面使用
@Service("roleService")
public class RoleService implements IRoleService {
//注入需要的Mapper实例,用于方法调用
@Autowired
private RoleMapper roleMapper;
@Override
public Role findRoleById(String id) {
return roleMapper.selectByPrimaryKey(id);
}
}
3、编写 controller
package com.wishuok.controller;
import com.wishuok.pojo.Role;
import com.wishuok.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/role")
public class RoleController {
@Autowired
private IRoleService roleService;
@RequestMapping(value = "/getRoleById/{id}", method = RequestMethod.GET)
public String findById(@PathVariable("id") String id, Model model){
Role role = roleService.findRoleById(id);
model.addAttribute("role", role);
return "showRole";
}
}
4、编写showRole.jsp
视图
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入jstl标签库,用于页面判断操作--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>title</title>
</head>
<body>
<h2>角色信息:</h2>
<c:if test="${role==null}">
该角色不存在
</c:if>
${role.id}
${role.roleName}
${role.note}
</body>
</html>
六、运行
1、Run/Debug config 新增:
Local
的Tomcat Server
Deployment
标签页配置参考:image.png
2、运行
浏览器输入地址:http://localhost/role/getRoleById/216e8f7c28a846a78de10d7b8e1acf34
可看到如下输出:
七、示例建表语句
/*
Navicat Premium Data Transfer
Source Server : 192.168.109.128
Source Server Type : MySQL
Source Server Version : 80015
Source Host : 192.168.109.128:3306
Source Schema : test
Target Server Type : MySQL
Target Server Version : 80015
File Encoding : 65001
Date: 12/05/2019 22:11:18
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`RoleName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`Note` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('216e8f7c28a846a78de10d7b8e1acf34', 'testmap', '2019-04-05 16:27:33');
INSERT INTO `role` VALUES ('3c12bab2bc2e49e193b6ce621c9e6aab', 'testmap', '2019-04-05 16:26:36');
INSERT INTO `role` VALUES ('81494e11f3f6422983d3517a8f8aff6f', 'testmap', '2019-04-05 16:24:14');
INSERT INTO `role` VALUES ('9e4e9554a0134b5bb62e9486f9319318', 'normal', '2019-04-05 08:24:05');
INSERT INTO `role` VALUES ('bec7230480c4480bb4c85a79b3f741cd', 'testupdate', '2019-04-05 08:31:48');
INSERT INTO `role` VALUES ('cda3e3a9c4aa415da505920ffc3afe2a', 'testupdatenew', '2019-04-05 08:31:48');
INSERT INTO `role` VALUES ('d4ef435531cb40e6a7d425556b1dc7ce', 'admin', '2019-04-05 08:23:54');
SET FOREIGN_KEY_CHECKS = 1;
网友评论