SpringBoot整合Mybatis篇
实现单表mybatis整合
准备sql:
--创建数据库
create database if not exists `mybatis`;
--修改数据库默认字节编码
alter database `mybatis` character set utf8;
--使用数据库
use `mybatis`;
--创建表
create table if not exists `student`(
`id` int(11) not null Auto_Increment comment '编号',
`name` varchar(255) not null comment '姓名',
`sex` varchar(255) not null comment '性别',
primary key(`id`)
)engine=InnoDB default charset =utf8;
目录结构:
![](https://img-blog.csdnimg.cn/396ff472c0b24d029eb717069999a8ba.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5oiR5oS_5Li65LiA57KS5rKZ,size_20,color_FFFFFF,t_70,g_se,x_16)
mybatis、mysql驱动、lombok依赖
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--lombok 在springboot仓库中版本号-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
yaml配置文件:
#mysql驱动就是连接数据库,mybatis就是映射
# 应用名称
spring:
application:
name: my #自己SpringBootApplication
datasource:
# 数据库驱动:
driver-class-name: com.mysql.cj.jdbc.Driver
# 数据库驱动:
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf-8
# 数据库用户名&密码:
username: root
password: 123456
# 数据源名称
name: defaultDataSource
mybatis:
#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件
mapper-locations: classpath*:/mappers/*.xml
#指定Mybatis的实体目录,如同取别名
type-aliases-package: com.my.entity
entity实体类:
package com.my.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private Integer id;
private String name;
private String sex;
}
@Mapper与@MapperScan的关系
mapper持久层:@Mapper对单个数据层接口注入到spring容器中
package com.my.mapper;
import com.my.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Delete;
import java.util.List;
@Mapper
public interface StudentMapper {
List<Student> findAll();
int insertTo(Student student);
@Delete("delete from student where id=#{id}")
int deleteStudent(Integer id);
}
MyApplication主启动类:@MapperScan是对多个数据层接口的注入
package com.my;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.my.mapper")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
studentMapper.xml文件,SQL
<?xml version="1.0" encoding="UTF8" ?>
<!--含有中文注释报错,删除utf-8中的”-“-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.my.mapper.StudentMapper">
<!-- 数据库中的字段名与实体类中的属性名不一致:
一使用as:
select password as pwd form student
二使用resultMap映射:
<resultMap id="studentMap" type="student">
<result column="password" property="pwd"/>
</resultMap>
-->
<!-- parameterType="com.my.entity.Student",使用别名就可以直接使用实体类小写 -->
<insert id="insertTo" parameterType="student">
insert into student(id,name,sex) value (#{id},#{name},#{sex});
</insert>
<select id="findAll" resultType="com.my.entity.Student">
select * from student;
</select>
</mapper>
MyApplicationTest测试类:
package com.my;
import com.my.entity.Student;
import com.my.mapper.StudentMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class MyApplicationTests {
@Autowired
private StudentMapper studentMapper;
@Test
public void findAllStudent() {
List<Student> students=studentMapper.findAll();
for (Student student:students) {
System.out.println(student.toString());
}
}
@Test
public void insertStudent(){
Student student=new Student(5,"nini","男");
int a=studentMapper.insertTo(student);
System.out.println(a);
}
@Test
public void delStudent(){
int b=studentMapper.deleteStudent(2);
System.out.println(b);
}
}
实验自我体验
自我实验报错有:
一、.properties与.yaml配置文件中,mybatis.mapper-locations写法不一致,
.properties:
mybatis.mapper-locations=classpath:mappers/*.xml
.yaml:
mybatis:
mapper-locations: classpath*:/mappers/*.xml
二、mapper.xml文件,接收接口传来的参数,在parameterType="全路径",不然就要在yaml或者properties文件中,定义包或者类别名,使其自动匹配,会按照小写等匹配
mybatis:
#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件
type-aliases-package: com.my.entity
三、存入的文件有乱码,一优先考虑配置文件中,数据库连接配置characterEncoding=utf-8没,之后在考虑其他,如数据库是否是默认字节编码等等
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf-8
四、对于简单的sql我们,可以直接在mapper接口的方法上直接写入,如同以下
@Delete("delete from student where id=#{id}")
int deleteStudent(Integer id);
五、写代码一定要仔细,尽量避免不必要的麻烦!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)