公司刚开发一个ssm架构的项目,同事推荐了mybatis的一个插件,发现上手容易,高效简洁。下面是官方的文档: 传送门请进
我的demo目录:注意SpringBoot的启动类的位置
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatisplus-spring-
boot-starterartifactId>
<version>1.0.4version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plusartifactId>
<version>2.0.7version>
dependency>
注意: mybatis-plus 自动的维护了mybatis以及mybatis-spring的依赖,在springboot中这三者不能同时的出现,避免版本的冲突,表示:跳进过这个坑。。。
2、application.properties 文件;
#tomcat\u7F16\u7801
server.port=8081
# salt used for generate token
token-random-salt=restyle@123
# \u6570\u636E\u6E90\u914D\u7F6E
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_stu_crm?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis-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;
/**
* 数据源配置
*/
@Configuration
public 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 表数据层控制接口
*/
@Repository
public interface StudentMapper extends BaseMapper {
List findAllStudent();
List findSomeColumn();
void deleteById(Integer id);
void updateByPrimarKeySelective(Student student);
void saveStudent(Student student);
List 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 findStuByGender(Integer gender);
}
注意 : 如果在xml 中不写SQL的,可以使用注解的方式在此接口当中直接写SQL,实体和数据库表字段不一致,使用@Result注解来映射
6、 新建StudentMapper的配置文件:
<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 {
List findAllStudent();
List findSomeColumn();
void deleteById(Integer id);
void updateByPrimarKeySelective(Student student);
void saveStudent(Student student);
Page findAllStudentPage(Page page);
List 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;
@Service
public class StudentServiceImpl extends ServiceImpl
implements StudentService {
@Override
public List findAllStudent() {
// TODO Auto-generated method stub
return baseMapper.findAllStudent();
}
@Override
public List 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 findAllStudentPage(Page page) {
// TODO Auto-generated method stub
page.setRecords(baseMapper.findAllStudentPage(page));
return page;
}
@Override
public List 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")
@Slf4j
public 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 = studentService.findAllStudent();
result.setData(student);
return result;
}
@RequestMapping("findSomeColumn")
public Result test2(){
Result result = new Result();
List 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 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 test5(@RequestBody Student student){
Result result = new Result();
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 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 wrapper = new EntityWrapper<>();
wrapper.eq("gender", 1);
Page page = getPage(pageNumber, pageSize);
Page stuPage = studentService.selectPage(page, wrapper);
result.setData(stuPage.getRecords());
return result;
}
/**
* 获取分页对象
* 每页显示数量
*/
private Page getPage(int pageNum,int pageSize){
return new Page(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扫描
@SpringBootApplication
public 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 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 {
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官方文档