MyBatis
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎
所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
开发步骤
1、添加依赖 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.yan</groupId>
<artifactId>20221201</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<description>雇员管理系统</description>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- MyBatis框架 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.31</version>
</dependency>
<!-- Servlet开发所需要的依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- jsp开发所需要的依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!-- JSTL标准标签库 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 为了简化javabean的编写所引入的工具 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<!-- 用于实现单元测试的支持 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>emp</finalName>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.11.v20180605</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<httpConnector>
<port>8080</port>
</httpConnector>
<webApp>
<contextPath>/emp</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>
2、定义数据库表
create table if not exists t_dept(
id bigint primary key auto_increment,
dept_name varchar(20) not null,
location varchar(50)
)engine=innodb default charset utf8mb4;
3、根据表结构定义对应的实体类
@Data
public class Dept implements Serializable {
private Long id;
private String deptName;
private String location;
}
4、定义映射元文件,用于指定对应关系和对应的SQL语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yan.dao.DeptMapper">
<!-- 结果集映射 resultSet转换为bean对象 -->
<resultMap id="baseMapper" type="com.yan.entity.Dept">
<id property="id" column="id" jdbcType="BIGINT"/>
<result property="deptName" column="dept_name" jdbcType="VARCHAR"/>
<result property="location" column="location" jdbcType="VARCHAR"/>
</resultMap>
<!-- 命名块 -->
<sql id="columns">
id,dept_name,location
</sql>
<!-- 查询对应的sql语句 -->
<select id="selectByExample" parameterType="DeptBean"
resultMap="baseMapper">
select <include refid="columns"/> from t_dept where 1=1
<!-- 动态sql语句 -->
<if test="id!=null">
and id=#{id}
</if>
<if test="deptName!=null and deptName!=''">
and dept_name = #{deptName}
</if>
<if test="location!=null and location!=''">
and location like #{location}
</if>
</select>
<select id="selectByMap" parameterType="map" resultMap="baseMapper">
select <include refid="columns"/> from t_dept where 1=1
<if test="noId!=null">
and id != #{noId}
</if>
<if test="deptName!=null">
and dept_name=#{deptName}
</if>
</select>
<select id="loadById" parameterType="long" resultMap="baseMapper">
select <include refid="columns"/> from t_dept where id=#{id}
</select>
<!-- 插入对应的SQL语句 -->
<insert id="insertDept" parameterType="DeptBean" useGeneratedKeys="true"
keyProperty="id">
insert into t_dept(dept_name
<if test="location!=null">
,location
</if>
) values(#{deptName}
<if test="location!=null">
,#{location}
</if>
)
</insert>
<delete id="deleteById" parameterType="long">
delete from t_dept where id=#{id}
</delete>
<update id="updateById" parameterType="DeptBean">
update t_dept set id=#{id}
<if test="deptName!=null">
,dept_name=#{deptName}
</if>
<if test="location!=null">
,location=#{location}
</if>
where id=#{id}
</update>
</mapper>
5、定义核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 运行环境配置 -->
<settings>
<!--设置日志输出 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 类型别名的定义 -->
<typeAliases>
<typeAlias type="com.yan.entity.Dept" alias="DeptBean"/>
</typeAliases>
<!-- 运行环境配置 -->
<environments default="yan">
<environment id="yan">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///test?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--注册映射元文件 -->
<mappers>
<mapper resource="mapper/DeptMapper.xml"/>
</mappers>
</configuration>
6、定义业务
由于不能直接分析需求完成业务的定义,所以建议优先考虑先定义UI层,在编程的过程中总结出所需要的业务方法
首先定义业务接口
public interface IDeptServ {
List<Dept> getAllDepts();
boolean existName(String deptName);
boolean create(Dept dept);
Dept getById(Long id);
List<Dept> findByNoIdAndName(Long id, String deptName);
boolean modifyById(Dept dept);
}
然后定义业务实现类
package com.yan.biz;
import com.yan.dao.DeptMapper;
import com.yan.entity.Dept;
import com.yan.util.MyBatisSessionFactory;
import com.yan.util.StringUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DeptServImpl implements IDeptServ {
@Override
public List<Dept> getAllDepts() {
DeptMapper deptMapper = MyBatisSessionFactory.getMapper(DeptMapper.class);
List<Dept> deptList = deptMapper.selectByExample(null);
return deptList;
}
@Override
public boolean existName(String deptName) {
if (StringUtil.isBlank(deptName))
throw new IllegalArgumentException("参数不允许为空!");
DeptMapper deptMapper = MyBatisSessionFactory.getMapper(DeptMapper.class);
Dept dept = new Dept();
dept.setDeptName(deptName);
List<Dept> deptList = deptMapper.selectByExample(dept);
return deptList != null && deptList.size() > 0;
}
@Override
public boolean create(Dept dept) {
if (dept == null || StringUtil.isBlank(dept.getDeptName()))
throw new IllegalArgumentException("参数不允许为空!");
if (existName(dept.getDeptName())) {
throw new IllegalArgumentException("部门名称不允许重复!");
}
DeptMapper deptMapper = MyBatisSessionFactory.getMapper(DeptMapper.class);
int res = deptMapper.insertDept(dept);
return res > 0;
}
@Override
public Dept getById(Long id) {
if (id == null || id < 0)
throw new IllegalArgumentException("参数不合法!");
DeptMapper deptMapper = MyBatisSessionFactory.getMapper(DeptMapper.class);
return deptMapper.loadById(id);
}
@Override
public List<Dept> findByNoIdAndName(Long id, String deptName) {
if (id == null || StringUtil.isBlank(deptName))
throw new IllegalArgumentException("参数不合法!");
Map<String, Object> map = new HashMap<>();
map.put("noId", id);
map.put("deptName", deptName);
DeptMapper deptMapper = MyBatisSessionFactory.getMapper(DeptMapper.class);
return deptMapper.selectByMap(map);
}
@Override
public boolean modifyById(Dept dept) {
System.out.println(dept);
if (dept == null || dept.getId() == null || StringUtil.isBlank(dept.getDeptName()))
throw new IllegalArgumentException("参数不合法!");
DeptMapper deptMapper = MyBatisSessionFactory.getMapper(DeptMapper.class);
return deptMapper.updateById(dept)>0;
}
}
7、UI层 jsp+jstl负责显示 servlet负责调用业务类完成对应的业务逻辑处理