MyBatis--2(基于MyBatis的增删改查)

一、准备

  1. 准备数据库表emp
  2. 创建一个新的springboot工程,选择引入对应的起步依赖(mybatismysql驱动lombok)
  3. application.properties中引入数据库连接信息:数据库连接四要素
  4. 创建对应的实体类Emp(实体类属性采用驼峰命名–不留下划线)
  5. 准备Mapper接口EmpMapper

二、删除

1. 在Emp实体类中:

@Mapper
public interface EmpMapper {
    //根据ID删除数据
    @Delete("delete from emp where id=#{id}")  //将下列的id赋值给占位符
    public void delete(Integer id);//传入参数,动态的删除员工id
    //如果上述有返回值,则返回值代表操作所影响的记录数
}

2. 测试类中:

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {
    @Autowired
    private EmpMapper empmaper; 

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

3. 日志输出:

  • 可以在application.properties中,打开mybatis的日志,并指定输出到控制台。
#指定mybatis输出日志的位置,输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  • 在控制台中会产生预编译SQL,
  • 优点:性能更高(将预编译的文件进行缓存,下次执行时优先查看是否在有相同的SQL语句),更安全(防止SQL注入)

4.SQL注入

  • SQL注入是通过操作输入的数据来修改事先定义好的SQL语句,以达到执行代码对服务器进行攻击的方法。
//代码演示:在登录界面输入: ' or '1'='1
select count(*) from emp where username = 'wuieuwiueiwuiew' and password = '' or '1'='1'

5.参数占位符

  1. #{···}
  • 执行SQL时,会将#{···}替换为?,生成预编译SQL,会自动设置参数值。
  • 使用时机:参数传递,都使用#{···}
  1. ${···}
  • 拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入问题
  • 使用时机:如果对表名、列表进行动态设置时使用。

三、插入

1.SQL语句:

insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)
    values ('songyuanqiao','宋远桥',1,'71.jpg',2,2012-10-09',2,2022-10-0110:00:00', 2022-10-0110:00:00');

2.接口方法:

//在mapper类中键入代码:
@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})")

3.主键返回功能

  • 描述:在数据添加成功后,需要获取插入数据库数据的主键。如:添加套餐数据时,还需要维护套餐菜品关系表数据。
	// 主键返回的实现
    @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);  //将需要写入数据库的数据封装到实体类中

四、更新

1.接口方法

   // 更新员工:
    @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);

2.测试方法

 @Test
    public void testUpdate() {
        //构造员工对象
        Emp emp = new Emp();
        emp.setId(1);
        emp.setUsername("Tom5");
        emp.setName("汤姆5");
        emp.setImage("1.jpg");
        emp.setGender((short) 1);
        emp.setJob((short) 1);
        emp.setEntryDate(LocalDate.of(2000, 1, 1));
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);

        //执行更新员工操作
        empmaper.update(emp);
    }

五、查询

1.接口方法

//在mapper类中:
  //根据id查询员工
    @Select("select * from emp where id=#{id}") 
    public Emp getById(Integer id);

输出结果:Emp(id=1, username=Tom5, password=123456, name=汤姆5, gender=1, image=1.jpg, job=1, entrydate=2000-01-01, deptId=null, createTime=null, updateTime=null)

2.数据封装(基于上述输出字段的null值)

  • 实体类属性名和数据库表查询返回的字段一致,mybatis会自动封装。如果实体类属性名和数据库表查询返回的字段名不一致,不能自动封装。
  • 解决方案:(起别名,手动结果映射,开启驼峰命名)
  1. 方案一:给字段起别名,让别名与实体类属性一致
   // 给字段起别名,让别名与实体类属性一致
    @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);
  1. 方案二:通过@Results, @Result注解手动映射封装
    //方案二:通过@Results, @Result注解手动映射封装
    @Results({
            @Result(column = "dept_id", property = "deptId"),
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "update_time", property = "updateTime")
    })
    @Select("select * from emp where id=#{id}")
    public Emp getById(Integer id);
  1. 方案三:如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射,在Mapper类中写入原始的接口方法即可(推荐方法)
  • application.properties文件中配置:
#开启mybatis的驼峰命名自动映射开关  c__andy  ----->cAndy
mybatis.configuration.map-underscore-to-camel-case=true
  • 原始接口方法:
	//在mapper类中:
	//根据id查询员工
    @Select("select * from emp where id=#{id}") 
    public Emp getById(Integer id);

六、条件查询

1. 根据提供的文档–查询规则进行设计

2.接口方法

    //条件查询员工
    @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注入),处理方法如下:

-- mysql 语法中有concat的字符串拼接函数
select concat ( ' hello',' mysql', ' world' ) ;
-- 输出:hellomysqlworld

所以可以将上述的select语句改变成:

    //条件查询员工
    @Select("select * from emp where name like concat('%',#{name},'%') '%${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);
	//使用泛型接收多条数据

3.测试方法

    //根据条件查询员工
    @Test
    public void testList() {
        List<Emp> empList = empmaper.list("张", (short) 1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
        System.out.println(empList);
    }

猜你喜欢

转载自blog.csdn.net/m0_63144319/article/details/131030303