springboot整合mybatis基于xml配置CURD、多条件分页查询

版权声明:本站所提供的文章资讯、软件资源、素材源码等内容均为本作者提供、网友推荐、互联网整理而来(部分报媒/平媒内容转载自网络合作媒体),仅供学习参考,如有侵犯您的版权,请联系我,本作者将在三个工作日内改正。 https://blog.csdn.net/weixin_42323802/article/details/84591899
声明:使用JDK8、枚举、lombok 、springboot2.1.0、idea

对于繁琐的xml配置,其优点也很明显:
项目部署以后,若对项目进行扩展等,直接修改XML文件既可;
另外,在mybatis的XML配置中,XML的sql 复用也尤为常见;

下面完成对Users 类做一个基础的CURD,并融合些常用的SQL片段复用,动态SQL 、枚举类型完成对数据类型以及选项限定、以及分页等;

1、mybatis-spring-boot-starter是什么

mybatis-spring-boot-starter 是 MyBatis 帮助我们快速集成 Spring Boot 提供的一个组件包,使用这个组件可以做到以下几点:
构建独立的应用
几乎可以零配置
需要很少的 XML 配置

1.1、 在 test 数据库创建 users 表;

DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `userName` varchar(32) DEFAULT NULL COMMENT '用户名',
  `passWord` varchar(32) DEFAULT NULL COMMENT '密码',
  `user_sex` varchar(32) DEFAULT NULL,
  `nick_name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

创建model 、
由于users表中 user_sex 列限定性别 男和女,所以采用枚举类型进行限定;

public @Data class User implements Serializable {
	private static final long serialVersionUID = 1L;
	private Long id;
	private String userName;
	private String passWord;
	private UserSexEnum userSex;
	private String nickName;
	//
	public User() {
	}
	public User(String userName, String passWord, UserSexEnum userSex) {
		this.userName = userName;
		this.passWord = passWord;
		this.userSex = userSex;
	}
}

创建枚举类;

package com.mybatis.neo.mybatisdemo.enums;

public enum UserSexEnum {
	MAN, WOMAN
}

1.2、 配置文件

mybatis-config 配置文件;

<configuration>
    <!-- 这样在使用mapper.xml 时候方便多了 -->
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer"/>
        <typeAlias alias="Long" type="java.lang.Long"/>
        <typeAlias alias="HashMap" type="java.util.HashMap"/>
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/>
        <typeAlias alias="ArrayList" type="java.util.ArrayList"/>
        <typeAlias alias="LinkedList" type="java.util.LinkedList"/>
    </typeAliases>
</configuration>

配置springboot的核心配置文件 application.yml

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.mybatis.neo.mybatisdemo.model
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: root

1.3、 mapper接口,以及mapper.xml 的配置

1.3.1、写 mapper接口
public interface User1Mapper {
	// curd 接口
    List<User> getAll();
    User getOne(Long id);
    void insert(User user);
    void update(User user);
    void delete(Long id);
    
   }
1.3.2、配置mapper.xml

使用sql 片段 Base_Column_List
把列 id, userName, passWord, user_sex, nick_name 放入

 <sql id="Base_Column_List">
        id, userName, passWord, user_sex, nick_name
    </sql>

1、查询所有 User
2、根据id 查询User

 <!--查询所有的user -->
    <select id="getAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from users
    </select>
    <!--查询一个user
    parameterType:语句中占位符的值的类型,写的是全路径名或别名,可以省略
    -->
    <select id="getOne" resultMap="BaseResultMap" parameterType="Long">
        select
        <include refid="Base_Column_List"/>
        from users where id=#{id}
    </select>
    <resultMap id="BaseResultMap" type="com.mybatis.neo.mybatisdemo.model.User">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <result column="userName" property="userName" jdbcType="VARCHAR"/>
        <result column="passWord" property="passWord" jdbcType="VARCHAR"/>
        <result column="user_sex" property="userSex" javaType="com.mybatis.neo.mybatisdemo.enums.UserSexEnum"/>
        <result column="nick_name" property="nickName" jdbcType="VARCHAR"/>
    </resultMap>

插入–>
更新–>
删除–>

   <insert id="insert">
        insert into users (userName,passWord,user_sex) values(#{userName},#{passWord},#{userSex})
    </insert>
    <!-- update的sql判断中不要少写, -->
    <update id="update">
        update users set
        <if test="userName!=null">userName=#{userName},</if>
        <if test="passWord!=null">passWord=#{passWord},</if>
        nick_name=#{nickName}
        where id=#{id}
    </update>
    <delete id="delete">
      delete  from users where id=#{id}
    </delete>

1.4、 创建测试类进行测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisDemoApplicationTests {
    @Resource
    private User1Mapper user1Mapper;
    //crud  分别进行测试
    @Test
    public void testUser() {
        user1Mapper.insert(new User("a2", "a123456", UserSexEnum.WOMAN));
//        List<User> userList = user1Mapper.getAll();
        User user = user1Mapper.getOne(1L);
//        user.setNickName("打豆豆");
//        user1Mapper.update(user);
//        user1Mapper.delete(1L);
        System.out.println(user);
    }
   } 

2、 使用 mybatis 进行多条件分页:

多条件分页查询是实际工作中最常使用的功能之一,MyBatis 特别擅长处理这类的问题。在实际工作中,会对分页进行简单的封装,方便前端使用。另外在 Web 开发规范使用中,Web 层的参数会以 param 为后缀的对象进行传参,以 result 结尾的实体类封装返回的数据。

下面给大家以 User 多条件分页查询

2.1 、 创建basePage ,作为分页的base 类;

public @Data class PageParam {
    /**
     * 定义起始行,当前页pageSize,当前页
     */
    private int beginLine;
    private Integer pageSize = 3;
    private Integer currentPage = 0;

    public int getBeginLine() {
        return pageSize * currentPage;
    }
}

2.2 、 UserParam 继承PageParam ,从对象 UserParam 中获取分页信息和查询条件既可;

public
@Getter
@Setter
class UserParam extends PageParam {
    private String userName;
    private String userSex;
}

2.3 、 封装 Page对象, 即分页数据,用于返回前端:

public @Data class Page<E> implements Serializable {
    private static final long serialVersionUID = -2020350783443768083L;

    private int currentPage = 1; //当前页数
    private long totalPage;       //总页数
    private long totalNumber;    //总记录数
    private List<E> list;        //数据集

    public static Page NULL = new Page(0, 0, 15, new ArrayList());

    public Page() {
        super();
    }

    /**
     * @param beginLine   当前页数
     * @param totalNumber 总记录数
     * @param pageSize    页大小
     * @param list        页数据
     */
    public Page(int beginLine, long totalNumber, int pageSize, List<E> list) {
        super();
        this.currentPage = beginLine / pageSize + 1;
        this.totalNumber = totalNumber;
        this.list = list;
        this.totalPage = totalNumber % pageSize == 0 ? totalNumber
                / pageSize : totalNumber / pageSize + 1;
    }

    public Page(PageParam pageParam, long totalNumber, List<E> list) {
        super();
        this.currentPage = pageParam.getCurrentPage();
        this.totalNumber = totalNumber;
        this.list = list;
        this.totalPage = totalNumber % pageParam.getPageSize() == 0 ? totalNumber
                / pageParam.getPageSize() : totalNumber / pageParam.getPageSize() + 1;
    }
}

2.4 、 在mapper接口中添加分页的方法:

  //  分页查询
    List<User> getList(UserParam userParam);
    //获取分页数目
    int getCount(UserParam userParam);

2.5 、 创建分页用到的 SQL 片段:

  <sql id="Base_Where_List">
        <if test="userName != null and userName != ''">and userName = #{userName}</if>
        <if test="userSex != null and userSex != ''">and user_sex = #{userSex}</if>
    </sql>

mapper.xml 中,查询分页数据
查询分页的数目:

 <!-- 分页显示 -->
    <select id="getList" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from users where 1=1
        <include refid="Base_Where_List"/>
        order by  id desc limit #{beginLine},#{pageSize}
    </select>
    <!-- 查看分了多少页-->
    <select id="getCount" resultType="Integer">
        select count(1) from users where 1=1 <include refid="Base_Where_List"/>
    </select>

2.6 、 创建测试类 ,进行分页测试:

    @Test
    public void contextLoads() {
        UserParam userParam=new UserParam();
        userParam.setUserSex("WOMAN");
        userParam.setCurrentPage(0);
        userParam.setPageSize(2);
        //查询 count 、list  封装成page 返回至前端
        // page中total 是long类型
        long count = user1Mapper.getCount(userParam);
        List<User> userList = user1Mapper.getList(userParam);
        //封装page 对象
        Page page = new Page(userParam,count,userList);
        System.out.println("page = " + page);
    }

源码下载:
https://github.com/medoo-Ai/mybatis-demo

猜你喜欢

转载自blog.csdn.net/weixin_42323802/article/details/84591899