Mybatis中mapper.xml进行相关的封装

Posted SmallCuteMonkey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis中mapper.xml进行相关的封装相关的知识,希望对你有一定的参考价值。

封装:把常用的条件用sql片段进行封装,也就是在maper/*.xml文件中。
User类:

package com.zjj.entity;

public class User{
   private Integer id;
   private String userName;
   private String userPwd;
   private String name;
   private String remark;

    public User() {
    }

    public User(Integer id, String userName, String userPwd, String name, String remark) {
        this.id = id;
        this.userName = userName;
        this.userPwd = userPwd;
        this.name = name;
        this.remark = remark;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\\'' +
                ", userPwd='" + userPwd + '\\'' +
                ", name='" + name + '\\'' +
                ", remark='" + remark + '\\'' +
                '}';
    }
}
UserDao:
package com.zjj.dao;

import com.zjj.entity.User;

import java.util.List;
import java.util.Map;

public interface UserDao {
    public int create(User user);
//    用Map来进行相关的增删改查是Mybatis默认的
    public int delete(Map<String,Object> map);

    public List<User> query(Map<String,Object> map);

    public int count(Map<String,Object> map);

    public User detail(Map<String,Object> map);

}

UserService类(这个类里面的业务也可以在untils包中写一个类进行相关的封装):

package com.zjj.service;

import com.zjj.dao.UserDao;
import com.zjj.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequestMapping("/user")
public class UserService {
    @Autowired //注入
    private UserDao userDao;
    @PostMapping("/create")
    public int create(User user){
//       User user1=new User("jlkj","klj","lkjklj","88");
        return userDao.create(user);


    }


    public int delete(Integer id){
        Map<String,Object> map=new HashMap<>();
        map.put("id",id);
        return userDao.delete(map);


    }
    public List<User> query(User user){

       return userDao.query((Map<String, Object>) user);
    }
}

uitls包中:
BeanMapUtils类:

package com.zjj.utils;


import org.springframework.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.Map;

/*
* Bean 转化为map
* */
public class BeanMapUtils {
/*
*
* 将对象转化为map
* @param bean
* */
  public static <T> Map<String,Object> beanToMap(T bean){
     Map<String,Object> map=new HashMap<>();
     if(bean!=null){
         BeanMap beanMap=BeanMap.create(bean);//spring为我们提供的将map转化为Bean的方法
         for (Object key:beanMap.keySet()
              ) {
             map.put(key+"",beanMap.get(key));

         }
     }


return map;



  }



//  把updata的方法的参数进行相关的改变
  public  static <T> Map<String,Object> beanToMapForUpdate(T bean){
      Map<String,Object> map=new HashMap<>();
      if(bean!=null){

          BeanMap beanMap=BeanMap.create(bean);
          for (Object key:beanMap.keySet()
          ) {
              map.put("update"+upperFistLatter(key+""),beanMap.get(key));

          }
      }
      return map;

  }
//使首字母大写
    private static String upperFistLatter(String letter) {
      char[] chars=letter.toCharArray();//字符串转化为字符数组
      if(chars[0]>='a'&&chars[0]<='z'){

          chars[0]= (char) (chars[0]-32);//A=a-32 这个是Ascall码中对应的相关的值
      }

        return new String(chars);//将字符数组转化为字符串
    }


}

utils包中的MapParameter类:
package com.zjj.utils;

import java.util.HashMap;
import java.util.Map;

public class MapParameter {
   //目标对象
    private Map<String,Object> paramMap=new HashMap<>();

    //私有构造
    private MapParameter(){

    }

//    每次调用都会产生一个MapParamter对象,而产生一个MapParamter对象会产生一个上面的目标对象
    public static MapParameter getInstance(){
        return new MapParameter();
    }

    public MapParameter add(String key,Object value){

        paramMap.put(key,value);
        return this;
    }
//    添加一个map
    public MapParameter add(Map<String,Object> map){
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            paramMap.put(entry.getKey(),entry.getValue());
            
        }
        return this;
    }
    
    
    
    

}

UserMapper.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zjj.dao.UserDao">
  <!--  private String userName;
    private String userPwd;
    private String name;
    private String remark;-->

    <resultMap id="userResultMap" type="com.zjj.entity.User">
        <id property="id" column="id"></id>
        <result property="userName" column="user_name"></result>
        <result property="userPwd" column="user_pwd"></result>
        <result property="name" column="name"></result>
        <result property="remark" column="remark"></result>


    </resultMap>

    <insert id="create" parameterType="com.zjj.entity.User" useGeneratedKeys="true" keyProperty="id">

        insert into ssmuser(user_name,user_pwd,name,remark) values(#{userName},#{userPwd},#{name},#{remark},)
    </insert>



<!--    用map是默认的可以直接拿过来使用-->
    <delete id="delete">
    delete  from ssuser

    <include refid="UserFindCriteria"></include>

    </delete>
    <update id="update">
        update ssuer


--         /*害怕更新查询起冲突所以我们可以改一下更新的参数*/
<include refid="UserUpdateCriteria"/>

        <include refid="UserFindCriteria"/>

    </update>
    <select id="count" resultType="int">
    select count(*) *from ssmuser
    <include refid="UserFindCriteria"/>

    </select>
    <select id="query" resultMap="userResultMap">
   select *from ssuer
   <include refid="UserFindCriteria"/>

    </select>
    <select id="detail">
        select *from ssuer
        <include refid="UserFindCriteria"/>
        limit 1

    </select>



<!--    封装的sql片段可以放在后面有利于观赏-->

    <!--   定义sql片段-->
    <sql id="UserFindCriteria">
        -- 这样可以按照任一的形式来删除
        <where>
            <if test="userName!=null and userName!=''">and user_name=#{userName}</if>
            <if test="userPwd!=null and userPwd!=''">and userPwd=#{userName}</if>
            /*这个是模糊删除*/
            <if test="name!=null and name!=''">and name like concat('%',#{name},'%')</if>
            <if test="remark!=null and remark!=''">and remark like concat('%',#{remark},'%')</if>



        </where>



    </sql>

    <!--    封装查询的数据-->
    <sql id="UserUpdateCriteria">
        <set>
            <if test="updateUserName!=null and userName!=''"> updateUserName=#{userName},</if>
            <if test="updateUserPwd!=null and userPwd!=''">updateUserPwd=#{userName},</if>
            /*这个是模糊删除*/
            <if test="updateName!=null and name!=''"> updateName=#{name } ,</if>
            <if test="updateRemark!=null and remark!=''">updateRemark=#{remark} </if>


        </set>
    </sql>


</mapper>

然后可以用Mybatis进行相关的测试!!!!

以上是关于Mybatis中mapper.xml进行相关的封装的主要内容,如果未能解决你的问题,请参考以下文章

mybatis如何通过接口查找对应的mapper.xml及方法执行详解

Mybatis中Mapper.xml 文件使用注释遇到的坑

Mybatis中Mapper.xml 文件使用注释遇到的坑

myBatis mapper接口方法重载问题

mybatis plus 相关配置总结

mybatis plus 相关配置总结