Mybatis二 | 基础操作

目录

准备工作

使用注解配置SQL语句

删除操作

参数占位符 

预编译SQL 

增加操作

获取返回的主键

 更新操作

查询操作 

条件查询

使用XML映射文件的方式配置SQL语句


准备工作

  • 准备数据库表 emp
  • 创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)
  • application.properties中引入数据库连接信息
  • 创建对应的实体类 Emp(实体类属性采用驼峰命名)
  • 准备Mapper接口 EmpMapper

目录结构

建表语句

-- 部门管理
create table dept(
    id int unsigned primary key auto_increment comment '主键ID',
    name varchar(10) not null unique comment '部门名称',
    create_time datetime not null comment '创建时间',
    update_time datetime not null comment '修改时间'
) comment '部门表';

insert into dept (id, name, create_time, update_time) values(1,'学工部',now(),now()),(2,'教研部',now(),now()),(3,'咨询部',now(),now()), (4,'就业部',now(),now()),(5,'人事部',now(),now());



-- 员工管理
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 '员工表';

INSERT INTO emp
	(id, username, password, name, gender, image, job, entrydate,dept_id, create_time, update_time) VALUES
	(1,'jinyong','123456','金庸',1,'1.jpg',4,'2000-01-01',2,now(),now()),
	(2,'zhangwuji','123456','张无忌',1,'2.jpg',2,'2015-01-01',2,now(),now()),
	(3,'yangxiao','123456','杨逍',1,'3.jpg',2,'2008-05-01',2,now(),now()),
	(4,'weiyixiao','123456','韦一笑',1,'4.jpg',2,'2007-01-01',2,now(),now()),
	(5,'changyuchun','123456','常遇春',1,'5.jpg',2,'2012-12-05',2,now(),now()),
	(6,'xiaozhao','123456','小昭',2,'6.jpg',3,'2013-09-05',1,now(),now()),
	(7,'jixiaofu','123456','纪晓芙',2,'7.jpg',1,'2005-08-01',1,now(),now()),
	(8,'zhouzhiruo','123456','周芷若',2,'8.jpg',1,'2014-11-09',1,now(),now()),
	(9,'dingminjun','123456','丁敏君',2,'9.jpg',1,'2011-03-11',1,now(),now()),
	(10,'zhaomin','123456','赵敏',2,'10.jpg',1,'2013-09-05',1,now(),now()),
	(11,'luzhangke','123456','鹿杖客',1,'11.jpg',5,'2007-02-01',3,now(),now()),
	(12,'hebiweng','123456','鹤笔翁',1,'12.jpg',5,'2008-08-18',3,now(),now()),
	(13,'fangdongbai','123456','方东白',1,'13.jpg',5,'2012-11-01',3,now(),now()),
	(14,'zhangsanfeng','123456','张三丰',1,'14.jpg',2,'2002-08-01',2,now(),now()),
	(15,'yulianzhou','123456','俞莲舟',1,'15.jpg',2,'2011-05-01',2,now(),now()),
	(16,'songyuanqiao','123456','宋远桥',1,'16.jpg',2,'2010-01-01',2,now(),now()),
	(17,'chenyouliang','123456','陈友谅',1,'17.jpg',NULL,'2015-03-21',NULL,now(),now());

 Emp.java

package com.itheima.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    private Integer id;
    private String username;
    private String password;
    private String name;
    private Short gender;
    private String image;
    private Short job;
    private LocalDate entrydate;
    private Integer deptId;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

使用注解配置SQL语句

删除操作

EmpMapper.java

@Mapper
public interface EmpMapper {
    //根据id删除数据
    @Delete("delete from emp where id = #{id}")
    public void delete(Integer id);//可以有返回值,返回影响的记录数,将void改成int

}

SpringbootMybatisCrudApplicationTests.java

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testDelete(){
        empMapper.delete(17);
    }

}

运行后发现删除成功

  参数占位符 

参数传递时使用#{},执行SQL时,会将#{…}替换为?,生成预编译SQL,会自动设置参数值。

对表名、列表进行动态设置时使用${},直接将参数拼接在SQL语句中,存在SQL注入问题。

预编译SQL 

性能更高,更安全(防止SQL注入)

可以在application.properties文件中加入如下指令,可以在控制台查看mybatis日志

#配置mybatis的日志,指定输出到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

在mybatis的Mapper接口中声明的SQL语句使用的#{}占位符,#{}会被?替代,生成预编译SQL

增加操作

EmpMapper

@Mapper
public interface EmpMapper {
    //根据id删除数据
    @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" +
            " values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")//注意驼峰命名法

    public void insert(Emp emp);

}

SpringbootMybatisCrudApplicationTests.java

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testInsert(){
        Emp emp = new Emp();
        emp.setUsername("aw");
        emp.setName("awaw");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2000,1,1));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);
        empMapper.insert(emp);
    }

}

运行后发现新增成功

获取返回的主键

@Options(keyProperty = "id",useGeneratedKeys = true)

会自动将生成的主键值赋值给emp对象的id属性

EmpMapper

@Mapper
public interface EmpMapper {
    //根据id删除数据
    @Options(keyProperty = "id",useGeneratedKeys = true)//会自动将生成的主键值赋值给emp对象的id属性
    @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)" +
            " values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")

    public void insert(Emp emp);

}

SpringbootMybatisCrudApplicationTests.java

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testInsert(){
        Emp emp = new Emp();
        emp.setUsername("tom3");
        emp.setName("tom3");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2000,1,1));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);
        empMapper.insert(emp);
        System.out.println(emp.getId());
    }

}

运行结果如下,发现返回了主键

 更新操作

EmpMapper.java

@Mapper
public interface EmpMapper {
    @Update("update emp set username = #{username}, name = #{name}, gender = #{gender}, image = #{image}," +
            " job = #{job}, entrydate = #{entrydate}, dept_id = #{deptId},update_time = #{updateTime} where id = #{id}")
    public void update(Emp emp);

}

 SpringbootMybatisCrudApplicationTests.java

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testUpdate(){
        Emp emp = new Emp();
        emp.setId(21);
        emp.setUsername("hi");
        emp.setName("hello");
        emp.setImage("2.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2000,1,1));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);
        empMapper.update(emp);
    }

}

查询emp数据表

运行之后发现更改成功

查询操作 

EmpMapper.java

@Mapper
public interface EmpMapper {
    //根据id查询员工
    @Select("select * from emp where id = #{id}")
    public Emp getById(Integer id);

}

SpringbootMybatisCrudApplicationTests.java

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testSelect(){
        Emp emp = empMapper.getById(20);
        System.out.println(emp);
    }

}

运行结果如下 

发现deptId=null,createTime=null, updateTime=null三个字段无法被赋值

原因:实体类属性名和数据库表查询返回的字段名一致,mybatis会自动封装,不一致则不能自动封装

 解决上述字段无法被赋值问题方法如下

  • 起别名

起别名使别名与实体类属性名一致

EmpMapper.java内容如下

package com.itheima.mapper;

import com.itheima.pojo.Emp;
import org.apache.ibatis.annotations.*;

@Mapper
public interface EmpMapper {
    //根据id查询员工
    @Select("select id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id}")
    public Emp getById(Integer id);

}

运行结果如下 ,发现查询成功

  • 手动结果映射

 通过@Results,@Result注解手动封装映射

 EmpMapper.java内容如下

@Mapper
public interface EmpMapper {
    //根据id查询员工
    @Results({
            @Result(column = "dept_id",property = "deptId"),
            @Result(column = "create_time",property = "createTime"),
            @Result(column = "update_time",property = "updateTime")
    })
    @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id = #{id}")
    public Emp getById(Integer id);

}
  • 开启驼峰命名 

开启mybatis驼峰命名自动映射开关

 在applications.properties文件下加入如下内容

#开启mybatis驼峰命名自动映射开关
mybatis.configuration.map-underscore-to-camel-case=true

再次运行,发现查询成功

条件查询

查询入职时间为2010.1.1到2020.1.1之间的张姓男性

 SpringbootMybatisCrudApplicationTests.java

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testSelect(){
        List<Emp> list = empMapper.list("张",(short)1, LocalDate.of(2010,1,1),LocalDate.of(2020,1,1));
        System.out.println(list);
    }

}

如下为错误代码

@Mapper
public interface EmpMapper {
    @Select("select *  from emp where name like '%#{name}%' and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc;")
    public List<Emp> list(String name, short gender, LocalDate begin,LocalDate end);

}

 发现运行失败

 #{}不能出现在' '内,因为#{}会被?替代,最后为'%?%'

可以将#{}更改为${}

@Mapper
public interface EmpMapper {
    @Select("select *  from emp where name like '%${name}%' and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc;")
    public List<Emp> list(String name, short gender, LocalDate begin,LocalDate end);

}

运行发现查询成功 

 但由于生成的不是预编译SQL,存在性能低,不安全,存在SQL注入的问题

可以通过concat函数解决问题

@Mapper
public interface EmpMapper {
    @Select("select *  from emp where name like concat('%',#{name},'%') and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc;")
    public List<Emp> list(String name, short gender, LocalDate begin,LocalDate end);

}

运行发现查询成功

使用注解来配置XML语句会使代码更加简洁,但对于稍微复杂一点的语句,Java注解不仅力不从心还会让本就复杂的SQL语句更加混乱不堪。因此如果需要做一些复杂的操作,最好用XML映射语句

使用XML映射文件的方式配置SQL语句

使用XML映射文件有如下三种规范 

  • XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包名下
  • XML映射文件的namespace属性与Mapper接口的全类名保持一致
  • XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致

 在resources目录下创建包,注意目录之间需要用/来分隔

 在新包下创建文件EmpMapper.xml,名称与Mapper接口一致

在EmpMapper.xml中加入

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

EmpMapper.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.itheima.mapper.EmpMapper">
    <!--resultType单条记录所封装的内容-->
    <select id="list" resultType="com.itheima.pojo.Emp">
        select *  from emp where name like concat('%',#{name},'%') and gender = #{gender} and entrydate between #{begin} and #{end} order by update_time desc
    </select>
</mapper>

EmpMapper.java

package com.itheima.mapper;

import com.itheima.pojo.Emp;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface EmpMapper {
    public List<Emp> list(String name, short gender, LocalDate begin, LocalDate end);

}

调用SpringbootMybatisCrudApplicationTests.java发现查询成功

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值