mybatis plus实战:springboot 结合mybatis plus实例

前言

在这里插入图片描述

mybatis plus 不但能够像HIbernate一样针对对象操作数据库,也支持mybatis写原生的sql。而且可以根据表自动生成dao,service,controler层的增删改成方法,极大提升开发效率。

集成步骤:

  1. pom.xml 引入jar包:
	 <!-- 添加mybatisplus  -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatisplus-spring-boot-starter</artifactId>
            <version>${mybatisplus.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>${mybatisplus.version}</version>
        </dependency>
  1. application.yml 配置mybatis plus信息:
mybatis-plus:
  mapper-locations: classpath:com/*/mapper/*.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.common.model
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 0
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    #逻辑删除配置(下面3个配置)
    logic-delete-value: 1
    logic-not-delete-value: 0
    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
  configuration:
    #配置返回数据库(column下划线命名&&返回java实体是驼峰命名),自动匹配无需as(没开启这个,SQL需要写as: select user_id as userId)
    map-underscore-to-camel-case: true
    cache-enabled: false
    #配置JdbcTypeForNull, oracle数据库必须配置
    jdbc-type-for-null: 'null'
  1. Mapper.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.enjoypark.dao.StudentDao">

   <!-- 通用查询映射结果 -->
   <resultMap id="BaseResultMap" type="com.enjoypark.model.Student">
      <id column="id" property="id" />
      <result column="name" property="name" />
      <result column="sex" property="sex" />
      <result column="password" property="password" />
      <result column="create_time" property="createTime" />
   </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, name, sex, password, create_time
    </sql>

	<select id="selectListPage" resultMap="BaseResultMap">
	    SELECT <include refid="Base_Column_List" />
	    from student t
		where 1=1
		<if test="student!=null and student.id!=null">
			and t.id=#{student.id}
		</if>
		<if test="student!=null and student.name!=null">
			and t.name=#{student.name}
		</if>
		<if test="student!=null and student.sex!=null">
			and t.sex=#{student.sex}
		</if>
		<if test="student!=null and student.password!=null">
			and t.password=#{student.password}
		</if>
		<if test="student!=null and student.createTime!=null">
			and t.create_time=#{student.createTime}
		</if>
	</select>
</mapper>

  1. dao层编写:
package com.enjoypark.dao;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.enjoypark.model.Student;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

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

/**
 * <p>
  *  Dao 接口
 * </p>
 *
 * @author wangPeng
 * @since 2019-08-28
 */
@Repository()
public interface StudentDao extends BaseMapper<Student> {
    
    

	  /**
	   * mybatis-plus 和mybatis结合分页查询
	   * @return
	   */
	  public List<Student> selectListPage(Page<Map> mapPage, @Param("student") Student student);
}

  1. 编写service层接口:
package com.enjoypark.service;

import com.enjoypark.model.Student;
import com.baomidou.mybatisplus.service.IService;

import java.util.List;
import java.io.Serializable;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author wangPeng
 * @since 2019-08-28
 */
public interface StudentService extends IService<Student> {
    
    

    /**
	 * 分页查询
	 * mybatis-plus 和mybatis结合分页查询
	 * @param userQu
	 * @param firstStart
	 * @param pageSize
	 * @return
	 */
    public List<Student> getBypage(Student studentQu, int firstStart, int pagesize);

    /**
     * 查询表记录总数
     */
    public Long getAllCount(Student studentQu);

     /**
     * 根据实体保存
     */
    public int saveStudent(Student student);

    /**
     * 根据id查询实体
     */
    public Student getByID(Serializable studentID);

     /**
     * 根据实体Id更新
     */
    public int updateStudent(Student student);

    /**
     * 根据Id删除
     */
    public int deleteByID(Serializable studentID);
}

  1. 编写service impl实现类:
package com.enjoypark.service.impl;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;

import com.enjoypark.model.Student;
import com.enjoypark.dao.StudentDao;
import com.enjoypark.service.StudentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangPeng
 * @since 2019-08-28
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentDao, Student> implements StudentService {
    
    


    @Autowired
    private StudentDao studentDao;

	/**
	 * 分页查询
	 * mybatis-plus 和mybatis结合分页查询
	 * @param userQu
	 * @param firstStart
	 * @param pageSize
	 * @return
	 */
	@Override
    public List<Student> getBypage(Student studentQu, int firstStart, int pagesize)
    {
    
    
        return studentDao.selectListPage(new Page<>(firstStart,pagesize),studentQu);
    }

    /**
     * 查询表记录总数
     */
    @Override
    public Long getAllCount(Student studentQu){
    
    
        return studentDao.selectCount(new EntityWrapper<Student>()).longValue();
    }

     /**
     * 根据实体保存
     */
    @Override
    public int saveStudent(Student student){
    
    
    	return studentDao.insert(student);
    }

    /**
     * 根据id查询实体
     */
    @Override
    public Student getByID(Serializable studentID) {
    
    
    	return studentDao.selectById(studentID);
    }

     /**
     * 根据实体Id更新(updateById只更新有值得字段,updateAllColumById所有字段都更新)
     */
    @Override
    public int updateStudent(Student student){
    
    
    	return studentDao.updateById(student);
    }

    /**
     * 根据Id删除
     */
    @Override
    public int deleteByID(Serializable studentID){
    
    
       return studentDao.deleteById(studentID);
    }
}

  1. 编写control层类:
package com.enjoypark.controller;

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

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.util.DateUtil;
import com.util.SubmitMessage;

import com.enjoypark.service.StudentService;
import com.enjoypark.model.Student;

/**
 *
 * @author wangPeng
 * @since 2018-10-11
 * Student表的视图层
 */

@Controller
@Scope("prototype")
@SuppressWarnings("all")
@RequestMapping("/student")
public class StudentController {
    
    

    @Autowired
    public StudentService studentService;

    //分页时对应的列表用户信息
    private List<Student> studentList; // 把jsp中的字段变量封装
    // 异步操作操作返回的信息
    private SubmitMessage submitMessage = new SubmitMessage();
    private Student student;//当前实体

    /**
     * 跳转列表页面
     * @param request
     * @param model
     * @return
     */
    @RequiresPermissions("student:getStudent")
    @RequestMapping(value = "getStudent",method= RequestMethod.POST)
    public ModelAndView getStudent()
    {
    
    
    	return new ModelAndView("/student");
    }


	/**
     * 异步获取用户的信息列表
     * @param String page,String rows
     * @return Map<String, Object>
     */
    @RequiresPermissions("student:getStudentBypage")
    @RequestMapping(value ="getStudentBypage",method= RequestMethod.POST)
    //@ResponseBody 表示返回的数据不是html标签格式,如json,xml等数据
  	@ResponseBody
    public Map<String, Object> getStudentBypage(String page,String rows,Student student)
    {
    
    

        // 返回总记录数
        String total = Integer.toString(studentService.getAllCount(null).intValue());

        // 当前页
        int intPage;
        if (page == null || page.equals("0")){
    
    
            intPage = 1;
        }
        else{
    
    
            intPage = Integer.parseInt(page);
        }

        // 每页显示条数
        int number;
        if (rows== null || rows.equals("0")){
    
    
            number = 10;
        }else {
    
    
            number = Integer.parseInt(rows);
        }

        // 每页的开始记录 第一页为1 第二页为number +1
        int start = (intPage - 1) * number;

        // 查询所有的用户信息
        studentList = studentService.getBypage(student, start, number);

        Map<String, Object> jsonMap = new HashMap<String, Object>();// 定义map
        jsonMap.put("total", total);// total键 存放总记录数,必须的
        jsonMap.put("rows", studentList);// rows键 存放每页记录 list

        return jsonMap;
    }

	/**
     * 根据Id删除
     *
     * @return
     */
    @RequiresPermissions("student:deleteStudent")
    @RequestMapping(value="deleteStudent",method= RequestMethod.POST)
    @ResponseBody
    public SubmitMessage deleteSysuser(String studentID)
    {
    
    
		//获取删除成功的记录个数
				int result=studentService.deleteByID(Integer.parseInt(studentID));


        if(result>0){
    
    
    		submitMessage.setSuccess(true);
    		submitMessage.setInfo("删除成功");
    	}else{
    
    
    		submitMessage.setSuccess(false);
    		submitMessage.setInfo("数据库记录不存在");
    	}

        return submitMessage;
    }

    /**
     * 修改或新增前查询
     *
     * @return
     */
    @RequestMapping(value="saveorupdateStudentBefore",method= RequestMethod.GET)
    public ModelAndView saveorupdateStudentBefore(String studentID)
    {
    
    
    	ModelAndView modelAndView=new ModelAndView();
    	if(!StringUtils.isEmpty(studentID)){
    
    
    		student = studentService.getByID(Integer.parseInt(studentID));
    	}

        //设置前台接收的实体
        modelAndView.addObject("student",student);
        //设置页面视图
        modelAndView.setViewName("studentAdd");
        return modelAndView;
    }

     /**
     * 根据页面传递的信息,保存或修改数据库信息
     *
     * @return
     */
    @RequiresPermissions("student:saveorupdateStudent")
    @RequestMapping(value="saveorupdateStudent",method= RequestMethod.POST)
    @ResponseBody
    public SubmitMessage saveorupdateSysuser(Student student)
    {
    
    
		boolean isSave = student.getId() == null || student.getId().equals(0);

        String strtime = DateUtil.formatDateByFormat(new Date(),DateUtil.DATETIME_FORMAT2);

        int result=0;
        if (isSave){
    
    
            result=studentService.saveStudent(student);
        }
        else{
    
    
           result=studentService.updateStudent(student);
        }


        if(result>0){
    
    
    		submitMessage.setSuccess(true);
    		submitMessage.setInfo("删除成功");
    	}else{
    
    
    		submitMessage.setSuccess(false);
    		submitMessage.setInfo("数据库记录不存在");
    	}

        return submitMessage;
    }

}

  1. 效果测试:
    在这里插入图片描述

源码地址:

  1. 获取完整源码地址: https://download.csdn.net/download/penggerhe/11670196
  2. 公众号关注,免费领取:
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/penggerhe/article/details/108363729
今日推荐