搭建SSM框架mapper.xml映射开发方式
学习目标
本节我们将学习如何搭建SSM框架映射文件开发方式,也就是将sql
语句放在mapper.xml
文件中进行开发,适用于频繁更新需求的项目。
搭建方法
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>org.spring</groupId>
<artifactId>SSM02</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SSM02 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.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<!-- 统一配置Spring相关的版本信息 -->
<spring.version>5.3.24</spring.version>
<jackson.version>2.16.1</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- Spring core & mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>test</scope>
</dependency>
<!--aop切面编程相关 -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.1</version>
</dependency>
<!-- 数据库8.0.30 https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- 数据库连接池 -->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- mybatis驱动 https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!-- mybatis与spring环境依赖 https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- lombok插件依赖 https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<!-- 前端jstl标签 https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 前后端分离开发时,自动处理RequestBody的Json格式化 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- 前后端分离开发时,自动处理RequestBody的Json格式化 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- 前后端分离开发时,自动处理RequestBody的Json格式化 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>SSM02</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>
项目目录结构
先在资源目录增加config配置文件
在resources/config
目录下,新增三个配置文件,分别是:applicationContext.xml
、mvc.xml
、mybatis-config.xml
applicationContext.xml
配置文件内容如下;
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- @author e4glet -->
<!-- @since 2020年7月8日 -->
</beans>
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"
xmlns:aop="http://www.springframework.org/schema/aop"
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-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- @author e4glet -->
<!-- @since 2020年7月8日 -->
<!-- 配置Controller -->
<!-- 读取类包信息 -->
<!-- scan the package and the sub package -->
<context:component-scan base-package="com.spring.controller">
<!-- 排除对下面service包的注解 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
<!-- 扫描Aop包 -->
<context:component-scan base-package="com.spring" />
<!-- 切面 启动对@AspectJ注解的支持 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<!-- don't handle the static resource -->
<mvc:default-servlet-handler />
<!-- if you use annotation you must configure following setting -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- 默认是ISO-88859-1,避免乱码这里设置为UTF-8 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.DriverManagerDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/infosysdb?useUnicode=true&characterEncoding=utf-8&useSSL=false"/>
<property name="user" value="root"/>
<property name="password" value="x5"/>
</bean>
<!--
sqlSessionFactory配置
org.mybatis.spring.SqlSessionFactoryBean类来实例化sqlSessionFactory对象
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--属性注入:数据源-->
<property name="dataSource" ref="dataSource"/>
<!--读取mybatis的配置文件-->
<property name="configLocation" value="classpath:config/mybatis-config.xml"/>
<!--读取mapper.xml文件-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--动态代理对象-->
<bean class="org.mybatis.spring.mapper.MapperFactoryBean">
<!--注入会话工厂-->
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
<!--注入接口-->
<property name="mapperInterface" value="com.spring.mapper.UserMapper"/>
</bean>
<!-- 配置mvc的拦截器 可以配置多个,前后端分离开发不需要此项配置 -->
<!-- <mvc:interceptors>-->
<!-- <mvc:interceptor>-->
<!-- <!– 需要被拦截的路径 –>-->
<!-- <mvc:mapping path="/home/**" />-->
<!-- <mvc:mapping path="/admin/**" />-->
<!-- <!– 根据需要,可以拦截多个路径 –>-->
<!-- <!– <mvc:mapping path="/路径/**" /> –>-->
<!-- <!– 拦截处理的interceptor类 –>-->
<!-- <bean class="com.spring.interceptor.MemberInterceptor" />-->
<!-- </mvc:interceptor>-->
<!-- </mvc:interceptors>-->
<!-- 配置视图解析器 -->
<!-- configure the InternalResourceViewResolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/views/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
如果增加新的接口文件,则在mvc.xml
配置文件中增加动态代理对象的配置信息
<!--动态代理对象,注意这里每增加一个接口文件,这里要对应增加 -->
<bean class="org.mybatis.spring.mapper.MapperFactoryBean">
<!--注入会话工厂-->
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
<!--注入接口,OrderMapper为新接口的文件名-->
<property name="mapperInterface" value="com.spring.mapper.OrderMapper"/>
</bean>
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>
<!-- 全局setting配置,根据需要添加 --> <!-- 配置mapper
由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
但是必须遵循:mapper.xml和mapper.java文件同名且在一个目录
-->
<!-- <mappers></mappers> -->
</configuration>
配置Web.xml
将上述配置文件引入我们的项目,修改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 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">
<display-name>Archetype Created Web Application</display-name>
<!-- spring mvc配置相关 -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/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>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- spring配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param>
</web-app>
增加视图目录
在WEB-INF
目录增加视图目录views
,并在该目录下添加默认首页index.jsp
<%--
Created by IntelliJ IDEA.
User: eaglet
Date: 2024/4/23
Time: 14:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
Hello SpringMVC
</body>
</html>
新增用户对象模型
在com.spring.model
包下,新增实体类UserInfo.java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
private Integer user_id;
private String username;
private String userpass;
private Integer age;
private String sex;
private String address;
}
新增用户模块接口
在com.spring.mapper
包下,新增用户功能接口:UserMapper.java
import com.spring.model.UserInfo;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
/**
* 定义接口方法
* */
public List<UserInfo> getAllUsers();
}
编写接口实现
在com.spring.service
包下,新建UserService.java
import com.spring.mapper.UserMapper;
import com.spring.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
//注入数据接口
@Autowired
private UserMapper userMapper;
/**
* 通过接口注入自动实现方法功能,这里根据项目实际需要添加逻辑即可,所有数据相关的操作全部托管给MyBatis框架自动完成。
* */
public List<UserInfo> getAllUsers(){
return userMapper.getAllUsers();
}
}
在控制器类中编写请求
在com.spring.controller
包下,新建HomeController.java
import com.spring.model.UserInfo;
import com.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
public class HomeController {
@Autowired
UserService userService;
/**
* 默认首页
* */
@RequestMapping("/")
public ModelAndView index(){
ModelAndView mv = new ModelAndView("index");
return mv;
}
/**
* 默认首页
* */
@RequestMapping("/index")
public ModelAndView index1(){
ModelAndView mv = new ModelAndView("index");
List<UserInfo> userlist = userService.getAllUsers();
for(UserInfo u: userlist){
System.out.println(u.getUsername());
}
return mv;
}
}
在资源目录补充SQL映射文件
在resources/mapper
目录下新建sql
映射文件UserMapper.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.spring.mapper.UserMapper">
<!-- id标识为接口文件里的方法名称,resultType设置结果返回类型 -->
<select id="getAllUsers" resultType="com.spring.model.UserInfo">
select * from usertb
</select>
</mapper>
补充
添加tomcat
运行环境,然后运行项目即可,在浏览器输入http://localhost:8080/SSM02_war/index
,查看命令行终端运行结果。
该框架使用方法
Mapper映射文件
mapper映射文件常用标签
这里总结mapper
标签常用技巧
<trim>
检测标签,主要判断<if>
标签是否成立,成立则对应添加前后缀信息及前后缀过滤prefix
:前缀prefixOverrides
:前缀忽略suffix
:后缀suffixOverrides
:后缀忽略
<where>
会自动清除多余的and
和or
,<trim>
标签配合prefix
和prefixOverrides
使用,效果等同<where>
标签<set>
自动去除多余的逗号,
,<trim>
标签配合suffix
和suffixOverrides
使用,效果等同<set>
标签<where>
+<if>
时,必须以and
或者or
为开头,也就是和与或
语句<set>
+<if>
时,每个<if>
必须以逗号,
结尾
查询方法
<?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.spring.mapper.UserMapper">
<!-- 查询方法01:普通查询-->
<!-- id标识为接口文件里的方法名称,resultType设置结果返回类型 -->
<select id="getAllUsers" resultType="com.spring.model.UserInfo">
select * from usertb
</select>
<!-- 查询方法02:模糊查询-->
<!-- id标识为接口文件里的方法名称,parameterType为设置参数类型,resultType设置结果返回类型 -->
<select id="getUserBySearch" parameterType="com.spring.model.UserInfo" resultType="com.spring.model.UserInfo">
select * from usertb
<where>
<if test="username!=null">
and username like concat('%',#{username},'%')
</if>
</where>
</select>
<!-- 查询方法03:多条件查询-->
<!-- id标识为接口文件里的方法名称,parameterType为设置参数类型,resultType设置结果返回类型 -->
<select id="getUserByMutilCondition" parameterType="com.spring.model.UserInfo" resultType="com.spring.model.UserInfo">
select * from usertb
<where>
<if test="age!=null and age >0">
and age = #{age}
</if>
</where>
</select>
</mapper>
插入方法
<?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.spring.mapper.UserMapper">
<!-- 插入方法01:trim标签方法-->
<insert id="addUser" parameterType="com.spring.model.UserInfo">
insert into usertb
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username !=null">username,</if>
<if test="userpass !=null">userpass,</if>
<if test="age !=null">age,</if>
<if test="sex !=null">sex,</if>
<if test="address !=null">address,</if>
</trim>
<trim prefix="values(" suffix=")" suffixOverrides=",">
<if test="username !=null">#{username},</if>
<if test="userpass !=null">#{userpass},</if>
<if test="age !=null">#{age},</if>
<if test="sex !=null">#{sex},</if>
<if test="address !=null">#{address},</if>
</trim>
</insert>
</mapper>
更新方法
<?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.spring.mapper.UserMapper">
<!-- 更新方法01:trim标签方法-->
<update id="updateUserAgeById" parameterType="com.spring.model.UserInfo">
update usertb
<trim prefix="set" suffixOverrides=",">
<if test="age!=null">
age=#{age},
</if>
</trim>
</update>
<!-- 更新方法02:set标签方法-->
<update id="updateUserAgeById" parameterType="com.spring.model.UserInfo">
update usertb
<set>
<if test="age!=null">
age=#{age},
</if>
</set>
</update>
<!-- 更新方法03:带条件语句where标签方法-->
<update id="updateLoginTime" parameterType="com.payment.model.UserInfo">
update zf_usertb set login_time = Now()
<where>
<if test="username!=null">
username = #{username}
</if>
</where>
</update>
</mapper>
删除方法
<?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.spring.mapper.UserMapper">
<!-- 删除方法01:where标签方法-->
<delete id="deleteUserById" parameterType="com.spring.model.UserInfo">
delete from usertb
<where>
<if test="user_id!=null">
and user_id=#{user_id}
</if>
</where>
</delete>
<!-- 删除方法02:trim标签方法-->
<delete id="deleteUserById" parameterType="com.spring.model.UserInfo">
delete from usertb
<trim suffix="where" suffixOverrides="and | or">
<if test="user_id!=null">
and user_id=#{user_id}
</if>
</trim>
</delete>
</mapper>
上述mapper映射的sql
语句对应的接口定义
import com.spring.model.UserInfo;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
/**
* 定义接口方法
* 查询方法
* */
public List<UserInfo> getAllUsers();
/**
* 查询方法
* 模糊查询
* */
public List<UserInfo> getUserBySearch(UserInfo userInfo);
/**
* 查询方法
* 多条件查询
* */
public List<UserInfo> getUserByMutilCondition(UserInfo userInfo);
/**
* 更新方法
* */
public Integer updateUserAgeById(UserInfo userInfo);
/**
* 插入方法
* */
public Integer addUser(UserInfo userInfo);
/**
* 删除方法
* */
public Integer deleteUserById(UserInfo userInfo);
}
总结
这套配置和使用方法是众多企业内部SSM开发框架的常用方式之一,这个必须要学会。
标签:xml,mapper,spring,开发方式,import,org,com,public From: https://www.cnblogs.com/e4glet/p/18153202