Mybatis基础操作–查询
数据封装
- 实体类属性名和数据库表查询返回的字段名一致,mabatis会自动封装。
- 如果实体类属性名和数据库表查询返回的字段名不一致,不能自动封装。
package com.itheima.mapper;
import com.itheima.pojo.Emp;
import org.apache.ibatis.annotations.*;
import java.time.LocalDate;
import java.util.List;
@Mapper //在运行时,会自动生成该接口的实现类对象(代理对象),并且将该对象交给IOC容器管理
public interface EmpMapper {
//根据ID删除数据
//#:占位符;#{id}:动态把id传进去,id不是固定
//注意事项:如果mapper接口方法形参只有一个普通类型的参数,#{...}里面的属性名可以随便写,如:#{id},#{value}
//List<Emp>:需要返回多条查询结果
//条件查询员工(名字带张的男性,且入职时间在2020-01-01到2022-01-01之间,最后根据更新时间进行倒序排序
// "select * from emp where name like '%张%' and gender =1 and" +
// "entrydate between '2020-01-01' and '2022-01-01' order by update_time desc "
//'%#{name}%':里面的内容会变成字符串,但是字符串不能放在单引号之中;
// 使用$符可能会导致sql语句注入,消耗低,不安全(均不是最优解),可以使用concat字符串拼接函数
// @Select("select * from emp where name like '%${name}%' and gender =#{gender} and " +
// "entrydate between #{begin} and #{end} order by update_time desc ")
@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);
}
package com.itheima;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@SpringBootTest
class SpringbootMybatisCrudApplicationTests {
@Autowired
private EmpMapper empMapper;
@Test
public void selectList(){
List<Emp> empList=empMapper.list("张",(short)1,LocalDate.of(2010,1,1),LocalDate.of(2020,1,1));
System.out.println(empList);
}
}
参数名说明:map接口的方法当中,需要传递多个参数,需要在每一个参数前面加上一个注解param,来为这个参数指定一个名字,在#{参数名}就是我们通过注解指定的这个名字,是对应的
在使用springboot1.x版本或者单数使用mybatis时,在对map接口进行编译的过程当中不会保留方法的形参名称