准备
1. 创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)
可根据实际需要增添依赖
# 指定mybatis输出日志的位置, 输出控制台,便于查看运行过程
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
2. application.properties中引入数据库连接信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=1234
3. 准备数据库表,对应的实体类
实体类属性采用驼峰命名模式
-- 创建数据库
create database if not exists mybatis;
-- 使用数据库
use mybatis;
-- 员工管理(带约束)
create table emp (
id int unsigned primary key auto_increment comment 'ID',
username varchar(20) not null unique comment '用户名',
password varchar(32) default '123456' comment '密码',
name varchar(10) not null comment '姓名',
gender tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
image varchar(300) comment '图像',
job tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师',
entrydate date comment '入职时间',
dept_id int unsigned comment '部门ID',
create_time datetime not null comment '创建时间',
update_time datetime not null comment '修改时间'
) comment='员工表';
-- 员工数据略
4. 准备Mapper接口 EmpMapper
@Mapper
public interface EmpMapper {
}
实现
1. 新增数据(注解实现)
//mapper接口
//新增数据
@Options(keyProperty = "id",useGeneratedKeys = true)
//#{...} 里面写的名称是对象的属性。
@Insert("insert into student(name, no, gender, phone, degree, violation_count, violation_score, class_id, create_time, update_time) " +
"values(#{name}, #{no}, #{gender}, #{phone}, #{degree}, #{violationCount}, #{violationScore}, #{classId}, #{createTime}, #{updateTime})")
void insert(Student student);
@Options:主键返回,在数据添加成功后,需要获取插入数据库数据的主键。
keyProperty = “id”:指定了实体对象中用于接收主键值的属性名,这里的id应该与实体类中的主键属性名一致;
useGeneratedKeys = true:表示使用数据库自动生成的主键值。当插入数据时,数据库会自动生成一个主键值,并将其赋值给id属性。
在Mybatis中提供的参数占位符有两种:${…}, #{…}。
#{…} : 执行SQL时,会将#{…}替换为?,生成预编译SQL,会自动设置参数值。 使用时机:参数传递,都使用#{…}
${…} : 拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入问题。 使用时机:如果对表名、列表进行动态设置时使用。
```java
//测试类
@Test
public void insert(){
Student student = new Student(null,"张三","001",1,"13012345678",2,1,2,262, LocalDateTime.now(),LocalDateTime.now());
studentMapper.insert(student);
System.out.println(student.getId());//获取id验证数据,可省略
}
2. 根据id查询数据(注解实现)
@Select("select * from student where id = #{id}")
Student getById(Integer id);
//测试类
@Test
public void getById(){
Student student = studentMapper.getById(1);
System.out.println(student);
}
3. 修改数据(xml文件实现动态SQL)
//修改数据
void update(Student student);
//<if>标签用于判断条件是否成立,使用test属性进行条件判断,如果条件为true,则拼接SQL
<update id="update">
update student
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="no != null">
no = #{no},
</if>
<if test="gender != null">
gender = #{gender},
</if>
<if test="phone != null">
phone = #{phone},
</if>
<if test="degree != null">
degree = #{degree},
</if>
<if test="violationCount != null">
violation_count = #{violationCount},
</if>
<if test="violationScore != null">
violation_score = #{violationScore},
</if>
<if test="classId != null">
class_id = #{classId},
</if>
update_time = now()
</set>
where id = #{id}
</update>
@Test
public void update(){
Student student = new Student();
student.setId(1);
student.setName("张三");
student.setNo("003");
studentMapper.update(student);
}
4. 条件查询(XML映射配置文件实现动态SQL)
查询条件:姓名(模糊)、学号(精确)、学历(精确)
//mapper接口
List<Student> findStudents(@Param("name") String name,@Param("no") String no,@Param("degree") Integer degree);
//xml文件
<select id="findStudents" parameterType="student" resultType="student">
select * from student
<where>
<if test="name != null">
name like concat('%',#{name},'%')
</if>
<if test="no != null">
and no = #{no}
</if>
<if test="degree != null">
and degree = #{degree}
</if>
</where>
</select>
@Test
public void findStudents() {
List<Student> findStudents = studentMapper.findStudents("张","004",1);
findStudents.forEach(System.out::println);
5. 批量删除(XML映射配置文件实现动态SQL)
既能单删,也能群删
//mapper
<delete id="deleteById">
delete from student where id in
<foreach collection="list" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
foreach属性介绍:
collection:集合名称 item:集合遍历出来的元素/项
separator:每一次遍历使用的分隔符
open:遍历开始前拼接的片段
close:遍历结束后拼接的片段
//xml文件
void deleteById(List<Integer> ids);
@Test
public void deleteById() {
List<Integer> ids = Arrays.asList(4);
studentMapper.deleteById(ids);
}
到此为止,MyBatis的基本功能实现完成,后续功能可在此基础上进行增删。