简介
MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射,避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。MyBatis可以使用简单的XML或注解配置和映射原生信息,并将接口和Java的POJOs(Plain Old Java Objects,普通Java对象)映射成数据库中记录。SpringBoot官方虽然没有对MyBatis进行整合,但是MyBatis团队自行适配了对应的启动器,进一步简化了MyBatis对数据的操作
1.pom.xml文件引入相关依赖:
<!--mybatis启动器-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
<!--MySql数据库连接驱动,默认是8.x版本,5.x版本的需要把版本改成5.x-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
2.在resource目录下编写配置文件
在application.yml配置文件中进行数据库连接配置
#MySql数据库连接配置 这里以mysql8为例
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: 用户名
password: 密码
url: jdbc:mysql://127.0.0.1:3306/数据库名称?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=UTC
#开启驼峰命名,按自己的需求选择,可开可不开
mybatis:
configuration:
map-underscore-to-camel-case: true
3.整合MyBatis的两种方式
以comment和User两个实体类为例
public class Comment{
private Integer id;
private String content;
private String aId;
}
import java.util.List;
public class User{
private Integer id;
private String title;
private String content;
private List<Comment> commentList;
}
3.1 方式一:使用注解的方式整合MyBatis
/**
* @Mapper注解表示该类是一个MyBatis接口文件,并保证能够被SpringBoot自动扫描到Spring容器中;
* 在该接口内部,分别通过@Select、@Insert、@Update、@Delete注解配合SQL语句完成了对数据库表中数据
* 的增上改查操作
*/
@Mapper
public interface CommentMapper{//类名一般是表对应的实体类名后跟Mapper
@Select("SELECT * FROM t_comment where id = #{id}")//查询语句
public Comment findById(Integer id);//调用查询语句的方法
@Insert("INSERT INTO t_commnet(content,author,a_id)"+
"values(#{conten},#{author,#{aId}}")//插入语句
public int insertComment(Comment comment);//调用插入语句的方法,以此类推
}
3.2 方式二使用配置文件的方式整合MyBatis
3.2.1 创建Mapper接口文件
/**
*@Mapper注解表明了该接口是一个Mapper接口文件
*该接口文件中声明了查询和更新文章操作的两个方法
*/
@Mapper
public interface UserMapper{
public user selectUser(Integer id);
public user updateUser(User user);
}
3.2.2创建XML文件
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.UserMpper">
<!--namespace="对应的Mapper接口文件包的路径"-->
<select id="方法名" resultType="">
sql语句
</select>
<update id="方法名" resultType="查询出的实体类数据的别名(类名)">
sql语句
</update>
</mapper>
3.2.3 配置XML映射文件
这里是在application.yml文件中配置
Mybatis:
#配置MyBatis的XML配置文件路径
mapper-locations: classpath:mapper/*.xml
#配置XML映射文件中的指定的实体类别名路径
type-aliases-package: com.itheima.domain