一、myBatis使用@Select查询

package com.gzgs.study01.web.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gzgs.study01.web.entity.User;
import com.gzgs.study01.web.param.UserParam;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;


//我们使用的@Mapper和@MapperScan并不是spring框架的注解,未在spring容器中注册为bean;
//@Repository标签可加可不加,不加的话@Autowired的时候会爆红而已,因为@MapperScan不是spring框架的注解
public interface UserMapper extends BaseMapper<User> {



    //通过用户名查询,为什么会加limit 1,因为我这里的返回类是User,如果查询到多条数据会报错
    @Select({"select * from t_user where user_name = #{userName} limit 1"})
    User getUserByName(String userName);


    //模糊查询
    @Select({"select * from t_user where user_name like concat('%',#{userName},'%') "})
    List<User> selectUserByName(String userName);


    /**
     * 复杂查询:自己搜索mapper@Select复杂查询
     * @param param
     * @return
     */
    @Select({"<script>"+
            " select t.* from t_user t"+
            " <where>"+
            " <if test='param.userName!= null and param.userName !=\"\" '>"+
            " and t.user_name like concat('%',#{param.userName},'%')"+
            " </if>"+
            " <if test='param.age!=null'>"+
            " and t.age = #{param.age} "+
            " </if>"+
            " </where>"+
            "</script>"
    })
    List<User> selectUserByParam(@Param("param") UserParam param);

}

二、单元测试

package com.gzgs.study01;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzgs.study01.web.entity.User;
import com.gzgs.study01.web.mapper.UserMapper;
import com.gzgs.study01.web.param.UserParam;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class StudyDemo01ApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        //一般都会在service层调用mapper
        //这里直接使用mapper封装好的selectOne方法查询
        //User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", 1));
        //System.out.println(user);


        //通过名称查询用户
        //User user = userMapper.getUserByName("测试用户");
        //System.out.println(user);


        //List<User> list = userMapper.selectUserByName("测试");
        //list.stream().forEach(a-> System.out.println(a.getUserName()));

        //UserParam userParam = new UserParam();
        //userParam.setAge(18);
        //userParam.setUserName("测试");
       //List<User> list = userMapper.selectUserByParam(userParam);
        //list.stream().forEach(a-> System.out.println(a.getUserName()));
    }

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐