基于SpringBoot的Mybatis-Plus插件整合
来源:互联网 发布:java识别图片文字 编辑:程序博客网 时间:2024/05/22 13:45
公司刚开发一个ssm架构的项目,同事推荐了mybatis的一个插件,发现上手容易,高效简洁。下面是官方的文档: 传送门请进
我的demo目录:注意SpringBoot的启动类的位置
1.首先添加pom文件的依赖:
<!-- mybatis的orm插件 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring- boot-starter</artifactId> <version>1.0.4</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.0.7</version> </dependency>
注意: mybatis-plus 自动的维护了mybatis以及mybatis-spring的依赖,在springboot中这三者不能同时的出现,避免版本的冲突,表示:跳进过这个坑。。。
2、application.properties 文件;
#tomcat\u7F16\u7801server.port=8081# salt used for generate tokentoken-random-salt=restyle@123# \u6570\u636E\u6E90\u914D\u7F6Espring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/db_stu_crm?useUnicode=true&characterEncoding=utf8&useSSL=falsespring.datasource.username=rootspring.datasource.password=rootspring.datasource.initialSize=5spring.datasource.minIdle=5spring.datasource.maxActive=20spring.datasource.maxWait=60000spring.datasource.timeBetweenEvictionRunsMillis=60000spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT 1 FROM DUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=falsespring.datasource.poolPreparedStatements=truespring.datasource.maxPoolPreparedStatementPerConnectionSize=20spring.datasource.filters=stat,wall,log4jspring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xmlmybatis-plus.typeAliasesPackage=com.cn.restyle.entity
数据源的配置:package com.cn.restyle.config;import javax.sql.DataSource;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.jdbc.datasource.DataSourceTransactionManager;import com.alibaba.druid.pool.DruidDataSource;/** * 数据源配置 */@Configurationpublic class DataSourceConfig { @Bean(name="dataSource") @ConfigurationProperties(prefix="spring.datasource") public DataSource dataSource(){ return new DruidDataSource(); } // 配置事物管理器 @Bean(name="transactionManager") public DataSourceTransactionManager transactionManager(){ return new DataSourceTransactionManager(dataSource()); }}
3、mybatis的配置
package com.cn.restyle.config;import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.baomidou.mybatisplus.plugins.PaginationInterceptor;@Configuration//扫描dao或者是Mapper接口@MapperScan("com.cn.restyle.mapper*")public class MybatisPlusConfig { /** * mybatis-plus 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor(){ PaginationInterceptor page = new PaginationInterceptor(); page.setDialectType("mysql"); return page; }}
4、 新建一个Student 的表
package com.cn.restyle.entity;import java.util.Date;import com.baomidou.mybatisplus.annotations.TableField;import com.baomidou.mybatisplus.annotations.TableId;import com.baomidou.mybatisplus.annotations.TableName;import com.baomidou.mybatisplus.enums.IdType;import com.fasterxml.jackson.annotation.JsonFormat;@TableName("tb_student")public class Student { @TableId(value="id",type=IdType.AUTO) private Integer id; @TableField("stu_name") private String stuName; @TableField("stu_number") private String stuNumber; private Integer gender; private Integer age; private String password; @TableField("stu_mobile") private String stuMobile; /** * 家长姓名 */ @TableField("par_name") private String parName; @TableField("par_mobile") private String parMobile; @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") @TableField("create_time") private Date createTime; @TableField("is_delete") private Integer isDelete; @TableField("role_id") private Integer roleId; // setter和getter方法省略}
注意: 在这儿注解: @TableName(“tb_student”),它是指与数据库的关联,意味着表对应的数据库的表名是tb_student.
再者,另一个注解,@TableFile(exist=false),表示Student类中有的属性,而对应的属性在表中没有这样的一个字段
5、 新建dao层接口StudentMapper:
package com.cn.restyle.mapper;import java.util.List;import org.apache.ibatis.annotations.Select;import org.springframework.stereotype.Repository;import com.baomidou.mybatisplus.mapper.BaseMapper;import com.baomidou.mybatisplus.plugins.Page;import com.baomidou.mybatisplus.plugins.pagination.Pagination;import com.cn.restyle.entity.Student;/*** Student 表数据层控制接口*/@Repositorypublic interface StudentMapper extends BaseMapper<Student> { List<Student> findAllStudent(); List<Student> findSomeColumn(); void deleteById(Integer id); void updateByPrimarKeySelective(Student student); void saveStudent(Student student); List<Student> findAllStudentPage(Pagination page); @Select("select * from tb_student where gender = #{gender}") @Results({ @Result(column="stu_name",property="stuName"), @Result(column="stu_mobile",property="stuMobile"), @Result(column="stu_number",property="stuNumber"), @Result(column="par_name",property="parName"), @Result(column="par_mobile",property="parMobile"), @Result(column="create_time",property="createTime") }) List<Student> findStuByGender(Integer gender);}
注意 : 如果在xml 中不写SQL的,可以使用注解的方式在此接口当中直接写SQL,实体和数据库表字段不一致,使用@Result注解来映射
6、 新建StudentMapper的配置文件:
<?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.cn.restyle.mapper.StudentMapper"> <resultMap id="BaseResultMap" type="com.cn.restyle.entity.Student"> <id column="id" property="id"></id> <result column="stu_name" property="stuName"></result> <result column="stu_mobile" property="stuMobile"></result> <result column="stu_number" property="stuNumber"></result> <result column="create_time" property="createTime"></result> <result column="role_id" property="roleId"></result> <result column="par_mobile" property="parMobile"></result> <result column="par_name" property="parName"></result> <result column="is_delete" property="isDelete"></result> </resultMap> <sql id="base_column_list"> stu_name,stu_mobile,stu_number,create_time,par_mobile,par_name </sql> <insert id="insertStudent" parameterType="com.cn.restyle.entity.Student"> insert into tb_student (stu_name,stu_mobile,stu_number,par_mobile,par_name) values (#{stuName},#{stuMobile},#{stuNumber},#{parMobile},#{parName}) </insert><!-- 拼接 --> <insert id="saveStudent" parameterType="com.cn.restyle.entity.Student"> insert into tb_student <trim prefix="(" suffix=")" suffixOverrides="," > <if test="stuName != null"> stu_name, </if> <if test="stuMobile"> stu_mobile, </if> <if test="stuNumber"> stu_number, </if> <if test="roleId"> role_id, </if> <if test="parMobile"> par_mobile, </if> <if test="parName"> par_name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="stuName != null">#{stuName},</if> <if test="stuMobile != null">#{stuMobile},</if> <if test="stuNumber!= null">#{stuNumber},</if> <if test="roleId !=null">#{roleId},</if> <if test="parMobile != null">#{parMobile},</if> <if test="parName !=null">#{parName},</if> </trim> </insert> <delete id="deleteById" parameterType="java.lang.Integer"> delete from tb_student where id = #{id} </delete> <update id="updateByPrimarKeySelective" parameterType="com.cn.restyle.entity.Student"> update tb_student <set> <if test="stuName ! = null"> stu_name = #{stuName} </if> <if test="password ! =null"> password = #{password} </if> <if test="stuMobile ! = null"> stu_mobile = #{stuMobile} </if> </set> </update> <update id="updateByprimaryKey"> update tb_student set stu_name = #{stuName} password = #{password} stu_mobile = #{stuMobile} </update> <select id="findSomeColumn" resultMap="BaseResultMap"> select <include refid="base_column_list" /> from tb_student </select> <select id="findAllStudent" resultMap="BaseResultMap"> select * from tb_student </select> <select id="findAllStudentPage" resultMap="BaseResultMap" resultType="Student"> select * from tb_student </select></mapper>
7、新建service层的类StudentService :
package com.cn.restyle.services;import java.util.List;import com.baomidou.mybatisplus.plugins.Page;import com.baomidou.mybatisplus.plugins.pagination.Pagination;import com.baomidou.mybatisplus.service.IService;import com.cn.restyle.entity.Student;public interface StudentService extends IService<Student> { List<Student> findAllStudent(); List<Student> findSomeColumn(); void deleteById(Integer id); void updateByPrimarKeySelective(Student student); void saveStudent(Student student); Page<Student> findAllStudentPage(Page<Student> page); List<Student> findStuByGender(Integer gender);}
8、service的实现类:
package com.cn.restyle.services.impl;import java.util.List;import org.springframework.stereotype.Service;import com.baomidou.mybatisplus.plugins.Page;import com.baomidou.mybatisplus.plugins.pagination.Pagination;import com.baomidou.mybatisplus.service.impl.ServiceImpl;import com.baomidou.mybatisplus.toolkit.PackageHelper;import com.cn.restyle.entity.Student;import com.cn.restyle.mapper.StudentMapper;import com.cn.restyle.services.StudentService;@Servicepublic class StudentServiceImpl extends ServiceImpl<StudentMapper,Student> implements StudentService { @Override public List<Student> findAllStudent() { // TODO Auto-generated method stub return baseMapper.findAllStudent(); } @Override public List<Student> findSomeColumn() { // TODO Auto-generated method stub return baseMapper.findSomeColumn(); } @Override public void deleteById(Integer id) { baseMapper.deleteById(id); } @Override public void updateByPrimarKeySelective(Student student) { baseMapper.updateById(student); } @Override public void saveStudent(Student student) { baseMapper.saveStudent(student); } @Override public Page<Student> findAllStudentPage(Page<Student> page) { // TODO Auto-generated method stub page.setRecords(baseMapper.findAllStudentPage(page)); return page; } @Override public List<Student> findStuByGender(Integer gender) { // TODO Auto-generated method stub return baseMapper.findStuByGender(gender); }}
测试的Controller:
package com.cn.restyle.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.baomidou.mybatisplus.mapper.EntityWrapper;import com.baomidou.mybatisplus.plugins.Page;import com.cn.restyle.entity.Student;import com.cn.restyle.services.StudentService;import com.cn.restyle.util.Result;import lombok.extern.slf4j.Slf4j;@RestController@RequestMapping("/v1/login")@Slf4jpublic class TestController { @Autowired private StudentService studentService; @RequestMapping("/register") public Result Register(@RequestBody Student student){ studentService.insert(student); return new Result(Result.OK,"保存成功"); } @RequestMapping("/findAllStudent") public Result test1(){ Result result = new Result(); List<Student> student = studentService.findAllStudent(); result.setData(student); return result; } @RequestMapping("findSomeColumn") public Result test2(){ Result result = new Result(); List<Student> stu = studentService.findSomeColumn(); result.setData(stu); return result; } @RequestMapping("deleteById/{id}") public Result test3(@PathVariable Integer id){ Result result = new Result(); studentService.deleteById(id); result.setMsg("删除成功"); return result; } @RequestMapping("updateByPrimarKeySelective") public Result test4(@RequestBody Student student){ Result result = new Result(); EntityWrapper<Student> entityWrapper = new EntityWrapper<>(); entityWrapper.eq("stu_mobile", student.getStuMobile()); Student stu = studentService.selectOne(entityWrapper); if (null != stu) { stu.setParName("my hero"); stu.setStuName("zxs"); } studentService.updateByPrimarKeySelective(stu); result.setData(stu); return result; } @RequestMapping("/saveStudent") public Result<Student> test5(@RequestBody Student student){ Result<Student> result = new Result<Student>(); studentService.saveStudent(student); result.setData(student); return result; } /** * 分页的方法 * @param pageNumber * @param pageSize * @return */ @RequestMapping("page/{pageNumber}") public Result findAllStuPage(@PathVariable Integer pageNumber, @RequestParam(defaultValue="6") Integer pageSize){ Result result = new Result(); Page page = new Page(pageNumber,pageSize); Page<Student> pageStu = studentService.findAllStudentPage(page); result.setData(pageStu.getRecords()); return result; } @RequestMapping("pageByGender/{pageNumber}") public Result findStuByGender(@PathVariable Integer pageNumber, @RequestParam(defaultValue="6") Integer pageSize){ Result result = new Result<>(); EntityWrapper<Student> wrapper = new EntityWrapper<>(); wrapper.eq("gender", 1); Page<Student> page = getPage(pageNumber, pageSize); Page<Student> stuPage = studentService.selectPage(page, wrapper); result.setData(stuPage.getRecords()); return result; } /** * 获取分页对象 * 每页显示数量 */ private <T> Page<T> getPage(int pageNum,int pageSize){ return new Page<T>(pageNum,pageSize); }}
SpringBoot的启动类:
package com.cn.restyle;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@MapperScan("com.cn.restyle.mapper") //配置mapper扫描@SpringBootApplicationpublic class CrmApplication { public static void main(String[] args) { SpringApplication.run(CrmApplication.class, args); }}
另外,对于EntityWrapper的条件拼接,基本可以实现SQL中常用的where,and,or,groupby, orderby等语法
@Test public void testSql(String str){ EntityWrapper<Student> wrapper = new EntityWrapper<>(); wrapper.eq("stu_name", str) .or() .eq("par_name", str) .orderBy("create_time", false) // 时间的倒叙排列 .limit(0, 1); // 取一条 Student stu = studentService.selectOne(wrapper); }
附:
我的Result 工具类
package com.cn.restyle.util;public class Result<T> { public static final Integer OK = 0; public static final Integer Error = -1; private Integer code; private String msg; private T data; public Result(){ this.code = OK; this.msg = "success"; } public Result(Integer code, String msg) { super(); this.code = code; this.msg = msg; } public Result(String msg, T data) { super(); this.msg = msg; this.data = data; } public Result(Integer code, String msg, T data) { super(); this.code = code; this.msg = msg; this.data = data; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; }}
参考文档:
mybatis-plus官方文档
- 基于SpringBoot的Mybatis-Plus插件整合
- SpringBoot系列2—整合Mybatis-plus
- springboot与mybatis的整合
- springboot与mybatis的整合
- JeeFast是一款基于SpringBoot+Mybatis-Plus+Bootstrap+Vue搭建的JAVA WEB快速开发平台
- springboot+mybatis-plus集成
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
- Springboot 整合 Mybatis 的完整 Web 案例
- Springboot 整合 Mybatis 的完整 Web 案例
- springboot整合mybatis最简单的例子
- Springboot 整合 Mybatis 的完整 Web 案例
- Springboot整合Mybatis的CallSettersOnNulls配置问题
- 简单的SpringBoot+Mybatis框架整合
- Springboot 整合 Mybatis 的完整 Web 案例
- “指针数组”和“数组指针”的区别、函数指针定义及引用
- java netty服务器简单例子
- python 装饰器
- 51Nod-1835-完全图
- 【西西学FPGA】Ubuntu环境下的Vivado使用及petalinux总结
- 基于SpringBoot的Mybatis-Plus插件整合
- c语言处理字符中的空格 函数
- 编程,初来乍到,多多关照。
- const修饰类成员和类对象
- Linux命令date日期时间和Unix时间戳互转
- springboot(八):RabbitMQ详解
- 简单的抽奖系统实现
- gbdt与逻辑回归融合
- IntelMediaSDK SampleDecode learning-3 AllocFrames函数