目录
1. 项目环境
- IDEA 2020.1.4
- Maven 3.6
- JDK 1.8
- SpringBoot 2.x
- Mysql 5.7
项目文件在GitHub(欢迎star⭐):
https://github.com/Gang-bb/Gangbb-SpringBoot
如有疑问或是建议,欢迎评论区留言或者QQ:949526365
声明:
1.在写文件时有些地方不小心把mybatis写成mabatis,所以截图中命名很多都是mabatis,github项目中已更正!
2. 在项目pom.xml文件中引入依赖
![image-20210122105610634](https://i-blog.csdnimg.cn/blog_migrate/890a957285a70fea8ba983c2b00923b3.png)
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
添加后Reload项目
3. 准备数据库相关
![image-20210123112004979](https://i-blog.csdnimg.cn/blog_migrate/a95d0a8660490d6a1b6b1f5f5dcf18c5.png)
主要用以下两个表做两种不同形式使用Mybatis
数据库导出myemployees.sql文件一同在Github对应的项目中(放在resources文件下)
4.基于注解形式使用Mybatis
4.1. 创建各层文件
总的文件目录:
![image-20210123104803804](https://i-blog.csdnimg.cn/blog_migrate/a058a1346886eb74712016683f9f3348.png)
当然模型层分包和命名是可以随意按喜好的。但是必要的文件:
XxxMapper、XxxService、XxxServiceImp、Xxx(实体类)、XxxController(测试用)
Xxx一般为一个表名,首字母要大写
4.2.1 Xxx实体类
package com.gangbb.gangbbspringbootmybatis.model.DO;
import java.io.Serializable;
/**
* @author : Gangbb
* @ClassName : Jobs
* @Description :
* @Date : 2021/1/23 10:33
*/
public class Jobs implements Serializable {
private String jobId;
private String jobTitle;
private Integer minSalary;
private Integer maxSalary;
public Jobs(String jobId, String jobTitle, Integer minSalary, Integer maxSalary) {
this.jobId = jobId;
this.jobTitle = jobTitle;
this.minSalary = minSalary;
this.maxSalary = maxSalary;
}
@Override
public String toString() {
return "Jobs{" +
"jobId='" + jobId + '\'' +
", jobTitle='" + jobTitle + '\'' +
", minSalary=" + minSalary +
", maxSalary=" + maxSalary +
'}';
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public Integer getMinSalary() {
return minSalary;
}
public void setMinSalary(Integer minSalary) {
this.minSalary = minSalary;
}
public Integer getMaxSalary() {
return maxSalary;
}
public void setMaxSalary(Integer maxSalary) {
this.maxSalary = maxSalary;
}
}
对应数据库中的jobs表(这里不应该用复数,小细节忽略…)
4.2.2 XxxMapper
做对数据库数据的处理
package com.gangbb.gangbbspringbootmybatis.model.dao;
import com.gangbb.gangbbspringbootmybatis.model.DO.Jobs;
import org.apache.ibatis.annotations.*;
/**
* @author : Gangbb
* @ClassName : JobsMapper
* @Description :
* @Date : 2021/1/23 10:34
*/
@Mapper
public interface JobsMapper {
@Insert("insert into jobs(job_id,job_title,min_salary,max_salary) values(#{jobId},#{jobTitle},#{minSalary},#{maxSalary})")
int add(Jobs job);
@Update("update jobs set job_title=#{jobTitle} where job_id=#{jobId}")
int update(Jobs job);
@Delete("delete from jobs where job_id=#{jobId}")
int deleteById(String jobId);
@Select("select * from jobs where job_id=#{jobId}")
@Results(id = "jobs",value= {
@Result(property = "jobId", column = "job_id", javaType = String.class),
@Result(property = "jobTitle", column = "job_title", javaType = String.class),
})
Jobs queryJobById(String jobId);
}
注意这里的@Mapper标签也可以换成@Repository。
两者的区别:
1.相同点
@Mapper和@Repository都是作用在dao层接口,使得其生成代理对象bean,交给spring 容器管理
对于mybatis来说,都可以不用写mapper.xml文件
2.不同点
@Mapper不需要配置扫描地址,可以单独使用,如果有多个mapper文件的话,可以在项目启动类中加入@MapperScan(“mapper文件所在包”),这样就不需要每个mapper文件都加@Mapper注解了
@Repository不可以单独使用(需要配合@MapperScan),否则会报错。
如果使用@Repository需要在启动文件上加上:
4.2.3 XxxService
service接口
package com.gangbb.gangbbspringbootmybatis.service;
import com.gangbb.gangbbspringbootmybatis.model.DO.Jobs;
/**
* @author : lyx
* @ClassName : JobsService
* @Description :
* @Date : 2021/1/22 8:34
*/
public interface JobsService {
int add(Jobs job);
int update(Jobs job);
int deleteById(String jobId);
Jobs queryJobById(String jobId);
}
4.2.4 XxxServiceImp
Xxxxservice接口实现类
package com.gangbb.gangbbspringbootmybatis.service.impl;
import com.gangbb.gangbbspringbootmybatis.model.DO.Jobs;
import com.gangbb.gangbbspringbootmybatis.model.dao.JobsMapper;
import com.gangbb.gangbbspringbootmybatis.service.JobsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author : lyx
* @ClassName : JobsServiceImp
* @Description :
* @Date : 2021/1/22 8:36
*/
@Service("JobsService")
public class JobsServiceImp implements JobsService {
@Autowired
private JobsMapper jobsMapper;
@Override
public int add(Jobs job) {
return jobsMapper.add(job);
}
@Override
public int update(Jobs job) {
return jobsMapper.update(job);
}
@Override
public int deleteById(String id) {
return jobsMapper.deleteById(id);
}
@Override
public Jobs queryJobById(String jobId) {
return this.jobsMapper.queryJobById(jobId);
}
}
4.2.5 XxxController
4.2. 配置文件
spring.datasource.name=myemployees_datasource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/myemployees?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
#实体类驼峰命名转成数据库中的下划线命名
mybatis.configuration.map-underscore-to-camel-case=true
#扫描实体类的路径
mybatis.type-aliases-package=com.gang.gangbbspringbootmabatis.model.bo
# xml路径
mybatis.mapper-locations=classpath:mappers/*.xml
5. 基于.xml使用Mybatis
与注解形式不相同的就是Mapper文件,所以其他文件不再赘述;还多了一个 XxxMapper.xml文件;配置文件需要声明.xml文件路径
.xml文件形式用另一个locations表做示例。
5.1 XxxMapper文件
package com.gangbb.gangbbspringbootmybatis.model.dao;
import com.gangbb.gangbbspringbootmybatis.model.DO.Locations;
import org.springframework.stereotype.Repository;
/**
* @author : Gangbb
* @ClassName : LocationsMapper
* @Description :
* @Date : 2021/1/23 10:34
*/
@Repository
public interface LocationsMapper {
int deleteByPrimaryKey(Integer id);
int insert(Locations locations);
Locations selectByPrimaryKey(Integer id);
int updateByPrimaryKey(Locations record);
}
不再用注解
5.2 XxxMapper.xml文件
![image-20210123112906684](https://i-blog.csdnimg.cn/blog_migrate/dfbf04a5784ebb3cb77b79142d1b6c6a.png)
增删查改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.gang.gangbbspringbootmabatis.model.dao.LocationsMapper">
<resultMap id="BaseResultMap" type="com.gang.gangbbspringbootmabatis.model.bo.Locations">
<id column="location_id" jdbcType="INTEGER" property="locationId" />
<result column="street_address" jdbcType="VARCHAR" property="streetAddress" />
<result column="postal_code" jdbcType="VARCHAR" property="postalCode" />
<result column="city" jdbcType="VARCHAR" property="city" />
<result column="state_province" jdbcType="VARCHAR" property="stateProvince" />
<result column="country_id" jdbcType="VARCHAR" property="countryId" />
</resultMap>
<sql id="Base_Column_List">
location_id, street_address, postal_code, city, state_province, country_id
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from locations
where location_id = #{locationId,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from locations
where location_id = #{locationId,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.gang.gangbbspringbootmabatis.model.dao.LocationsMapper">
insert into locations (location_id, street_address, postal_code,
city, state_province, country_id)
values (#{locationId,jdbcType=INTEGER}, #{streetAddress,jdbcType=VARCHAR}, #{postalCode,jdbcType=VARCHAR},
#{city,jdbcType=VARCHAR}, #{stateProvince,jdbcType=VARCHAR}, #{countryId,jdbcType=VARCHAR})
</insert>
<update id="updateByPrimaryKey" parameterType="com.gang.gangbbspringbootmabatis.model.dao.LocationsMapper">
update locations
set location_id = #{locationId,jdbcType=INTEGER},
street_address = #{streetAddress,jdbcType=VARCHAR},
postal_code = #{postalCode,jdbcType=VARCHAR},
city = #{city,jdbcType=VARCHAR},
state_province = #{stateProvince,jdbcType=VARCHAR},
country_id = #{countryId,jdbcType=VARCHAR}
where location_id = #{locationId,jdbcType=INTEGER}
</update>
</mapper>
5.3 配置文件声明XxxMapper.xml文件文件目录
#使用.xml形式使用mybatis声明.xml文件路径
mybatis.mapper-locations=classpath:mappers/*.xml
6.后记
xml文件形式使用Mybatis是目前的主流!因为注解形式没有真正发挥动态sql的灵活性并且可读性差,不好维护!