MyBatis基础操作-查询

目录

根据Id查询数据

数据封装

属性名和数据库表名不一致解决方法 

条件查询


据Id查询数据

mapper接口

@Select("select * from emp where id = #{id}")
    public User select(Integer id);

测试


    @Test
    public void empSelect(){
        User user = empMapper.select(14);
        System.out.println(user);
    }

但是发现有三个值为null,这是和Mybatis的数据封装有关系

数据封装

  • 实体类属性名和数据库表查询返回的字段名一致,Mybatis会自动封装
  • 如果实体类属性名和数据库表查询返回的字段名不一致,不能自动封装

属性名和数据库表名不一致解决方法 

方法一:给字段起别名,让别名与实体类属性一致

    @Select("select id,username,password,name,gender,emp.image,job,entrydate," +
            "dept_id deptId,create_time createTime,update_time updateTime from emp where id = #{id}")
    public User select(Integer id);

方法二:通过@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 User select(Integer id);

方法三:开启MyBatis 的驼峰命名自动映射(推荐)

即数据库字段a_cloumn自动映射为java属性名aCloumn

也就是说前提严格要求数据库为下划线命名,Java为驼峰命名

在application.properties中配置

mybatis.configuration.map-underscore-to-camel-case=true

条件查询

需求:根据输入的员工姓名,性别,入职时间搜索满足条件的员工信息

其中姓名支持模糊查询,性别精确查询,入职时间范围查询

根据修改时间排序

mapper接口添加查询方法,由于'%模糊查询%'是一个字符串拼接,所以#{}是不能在%%里面的,预编译的话就是'%?%',所以不能使用#{},可以使用${}进行字符串拼接

@Select("select * from emp where name like '%${name}%' and gender = #{gender} and " +
            "entrydate between #{begin} and #{end} order by update_time desc")
    public List<User> userList(String name, Short gender, LocalDate begin,LocalDate end);

测试


    @Test
    public void selectIf(){
        List<User> user = empMapper.userList("张", (short) 1,LocalDate.of(2000,1,1),LocalDate.of(2010,1,1));
        System.out.println(user);
    }

由于前面说过拼接SQL的安全性低,这里可以使用concat函数解决

@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<User> userList(String name, Short gender, LocalDate begin,LocalDate end);

补充:在springboot1.x中需要加@Param注解来对应#{}的参数

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

癞皮狗不赖皮

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

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

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

打赏作者

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

抵扣说明:

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

余额充值