MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)
当前,最新版本是MyBatis 3.5.7 ,其发布时间是2021年4月21日。
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
也可以在创建时进行选择,如下:
在application.properties文件中复制下面的配置信息:
spring.application.name=server-mybatis-demo
server.port=8000
## Mybatis
spring.datasource.url=jdbc:mysql://localhost:3306/db_test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
# 是自动配置别名,也就是设置这个之后,
# 在Mybatis的Mapper文件里就可以写对应的类名,而不用写全路径名了
mybatis.typeAliasesPackage=com.shenmazong.servermybatisdemo.pojo
mybatis.mapperLocations=classpath:/mapper/*.xml
logging.level.com.shenmazong.servermybatisdemo.mapper=debug
mybatis.configuration.map-underscore-to-camel-case=true
使用以上配置,有时候会提示如下错误信息
WARN: This connection is using TLSv1.1 which is now deprecated and will be removed in a future release of Connector/J.
如果出现上面错误,则把连接修改为下面配置即可:
spring.datasource.url=jdbc:mysql://localhost:3306/db_shop_0728?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for tb_student
-- ----------------------------
DROP TABLE IF EXISTS `tb_student`;
CREATE TABLE `tb_student` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学生ID',
`student_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '学生名字',
`age` int(11) NULL DEFAULT 0 COMMENT '学生年龄',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of tb_student
-- ----------------------------
INSERT INTO `tb_student` VALUES (1, '吕布', 13);
INSERT INTO `tb_student` VALUES (2, '赵云', 23);
INSERT INTO `tb_student` VALUES (3, '典韦', 25);
INSERT INTO `tb_student` VALUES (4, '黄盖', 35);
INSERT INTO `tb_student` VALUES (5, '马超', 26);
INSERT INTO `tb_student` VALUES (6, '张飞', 33);
SET FOREIGN_KEY_CHECKS = 1;
package com.shenmazong.servermybatisdemo.pojo;
import lombok.Data;
@Data
public class TbStudent {
private Integer id;
private String studentName;
private Integer age;
}
package com.shenmazong.servermybatisdemo.mapper;
import com.shenmazong.servermybatisdemo.pojo.TbStudent;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface TbStudentMapper {
@Select("select * from tb_student where id=#{id}")
TbStudent selectById(@Param("id") Integer id);
}
package com.shenmazong.servermybatisdemo.controller;
import com.shenmazong.servermybatisdemo.mapper.TbStudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@Autowired
TbStudentMapper tbStudentMapper;
@GetMapping(value = "/getStudentById")
public Object getStudentById(@RequestParam("id") Integer id) {
return tbStudentMapper.selectById(id);
}
}
<?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.shenmazong.servermybatisdemo.mapper.TbStudentMapper">
<select id="getOneById" resultType="com.shenmazong.servermybatisdemo.pojo.TbStudent">
select * from tb_student where id=#{id}
</select>
</mapper>
package com.shenmazong.servermybatisdemo.mapper;
import com.shenmazong.servermybatisdemo.pojo.TbStudent;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface TbStudentMapper {
@Select("select * from tb_student where id=#{id}")
TbStudent selectById(@Param("id") Integer id);
TbStudent getOneById(@Param("id") Integer id);
}
package com.shenmazong.servermybatisdemo.controller;
import com.shenmazong.servermybatisdemo.mapper.TbStudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@Autowired
TbStudentMapper tbStudentMapper;
@GetMapping(value = "/getStudentById")
public Object getStudentById(@RequestParam("id") Integer id) {
return tbStudentMapper.selectById(id);
}
@GetMapping(value = "/getOneById")
public Object getOneById(@RequestParam("id") Integer id) {
return tbStudentMapper.getOneById(id);
}
}
需要注意的是,xml文件存放路径已经要和application.properties文件中配置的扫描路径相匹配。
上面我们演示了如何使用MyBatis进行查询,但是在实际工作中,我们还有增加和修改,甚至还有删除。在增删改查操作中,没有太特别值得注意的地方,但是对于在增加操作中,如何获得自增主键的ID问题,让很多小伙伴掉到了坑了,那么接下来,我们就演示一下,看看如何获得自增的ID。
<insert id="addStudent" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert tb_student(id,student_name,age) values(#{id},#{studentName},#{age})
</insert>
主键自动生成,取决于数据库是否支持自增主键。实际上当设置了useGeneratedKeys=“true”,Mybatis会调用JDBC的getGeneratedKeys方法,并将获取的主键值赋值给keyProperty 指定的属性。
完整的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.shenmazong.servermybatisdemo.mapper.TbStudentMapper">
<select id="getOneById" resultType="com.shenmazong.servermybatisdemo.pojo.TbStudent">
select * from tb_student where id=#{id}
</select>
<insert id="addStudent" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert tb_student(id,student_name,age) values(#{id},#{studentName},#{age})
</insert>
</mapper>
package com.shenmazong.servermybatisdemo.mapper;
import com.shenmazong.servermybatisdemo.pojo.TbStudent;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface TbStudentMapper {
@Select("select * from tb_student where id=#{id}")
TbStudent selectById(@Param("id") Integer id);
TbStudent getOneById(@Param("id") Integer id);
Integer addStudent(TbStudent tbStudent);
}
@GetMapping(value = "/addStudent")
public Object addStudent(@RequestParam("studentName") String studentName,
@RequestParam("age") Integer age) {
TbStudent tbStudent = new TbStudent();
tbStudent.setStudentName(studentName);
tbStudent.setAge(age);
Integer studentId = tbStudentMapper.addStudent(tbStudent);
System.out.println("studentId="+studentId);
return tbStudent;
}
以上就是SpringBoot集成Mybatis的入门介绍,针对如何实现分页以及如何进行事务控制,会有单独的章节进行介绍。