崛起于Springboot2.X之整合FastMybatis、Mybatis精装版(44)

为什么80%的码农都做不了架构师?>>>   hot3.png

90%开发没用过的代码风格,用springboot的时候,既然无配置,那么就连mybatis的xml也不写了,也可以开发!

项目代码:==》点击

序言:集成fastmybatis框架,以及mybatis全注解的使用,fastmybatis框架自带mybatis,不需要配置mybatis,只配置fastmybatis,mybatis就可以使用

前提:@Autowired、@Qualifier、@Service(value="") 请先明白这几个注解的区别,代码会用到

目录结构图:

崛起于Springboot2.X之整合FastMybatis、Mybatis精装版(44)_第1张图片

UserControllers以fastmybatis框架写的增、删、改、差、分页、排序,开发中涉及到都写全了。

User2Controoler以mybatis方式写的增、删、改、差、排序等(分页自己网上找一下吧)

1、创建工程,勾选下面4个依赖

崛起于Springboot2.X之整合FastMybatis、Mybatis精装版(44)_第2张图片

2、pom文件依赖,添加fastmybatis


    net.oschina.durcframework
    fastmybatis-spring-boot-starter
    1.7.3

3、创建表结构

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `username` varchar(255) DEFAULT NULL COMMENT '用户名',
  `state` tinyint(4) DEFAULT NULL COMMENT '状态',
  `isdel` tinyint(4) DEFAULT NULL COMMENT '是否删除',
  `remark` text COMMENT '备注',
  `add_time` datetime DEFAULT NULL COMMENT '添加时间',
  `money` decimal(10,2) DEFAULT NULL COMMENT '金额',
  `left_money` float DEFAULT NULL COMMENT '剩下的钱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='用户表';

3、配置文件

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root

#fastmybatis
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

4、mybatisConfig.xml配置

放在文件下,不懂看目录图




    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    

5、实体类TUser

import com.gitee.fastmybatis.core.annotation.LogicDelete;
import lombok.Data;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class TUser {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    /** ID, 数据库字段:id */
    private Integer id;
    /** 用户名, 数据库字段:username */
    private String username;
    /** 状态, 数据库字段:state */
    private Byte state;

    /** 是否删除, 数据库字段:isdel */
    @LogicDelete
    private Boolean isdel;

    /** 备注, 数据库字段:remark */
    private String remark;

    /** 添加时间, 数据库字段:add_time */
    private Date addTime;

    /** 金额, 数据库字段:money */
    private BigDecimal money;

    @Column(name = "left_money")
    private float leftMoney;
}

6、工具类CreateDataUtil

public class CreateDataUtil {

    //方便下面添加用戶測試,num是创造多少个user实体类对象
    public static List getUsers(int num){
        List tUsers = new ArrayList<>();
        for (int i = 0;i getuserForMap(int id){
        Map map = new HashMap<>();
        map.put("username","更新后的大魔王");
        map.put("id",id);
        return map;
    }
}

改工具类只为了测试创建数据而已,调用接口的时候直接使用这些对象数据就可以了,省的在postman等工具编写参数了

7、Controller层

分别以mybatis、fastmybatis的形式对user进行增删改差、分页、排序、等操作,开发过程中写一种就可以了,写mybatis只是测试fastmybatis集成之后是不是可以使用mybatis原有的功能

import com.example.fastmybatis.entity.TUser;
import com.example.fastmybatis.service.TUserService;
import com.example.fastmybatis.util.CreateDataUtil;
import com.gitee.fastmybatis.core.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
* @Description: 使用fastmybatis框架测试增删改差相关接口
* @Author:Mujiutian
* @CreateDate:2019/6/8 0:53
* @UpdateUser:
*/

@RestController
@RequestMapping(value = "/user/fastmybatis")
public class UserController {

    @Autowired
    @Qualifier("userService")
    TUserService userService;

    /**
    * @description:添加一个用户
    * @author:MuJiuTian
    * @createDate: 2019/6/8 14:24
    */
    @PostMapping("/addUser")
    public String addUser(){
        userService.addUser(CreateDataUtil.getUser());
        return "以fastmybatis方式"+"添加一个对象数据成功";
    }

    /**
    * @description:添加num个用户
    * @author:MuJiuTian
    * @createDate: 2019/6/8 14:24
    */
    @PostMapping("/addUsers")
    public String addUsers(int num){
        userService.addUsers(CreateDataUtil.getUsers(num));
        return "以fastmybatis方式"+"批量添加数据成功";
    }

    /**
    * @description:逻辑意义上删除用户,如果你想把数据库中的数据真正删除,那么修改实体类中,把@LogicDelete这个注解去掉
    * @author:MuJiuTian
    * @createDate: 2019/6/8 14:24
    */
    @DeleteMapping(value = "/deleteUser")
    public String deleteUser(int id){
        userService.deleteUser(id);
        return "以fastmybatis方式"+"删除成功";
    }

    /**
    * @description:更新用户数据,需要该用户所有数据
    * @author:MuJiuTian
    * @createDate: 2019/6/8 14:25
    */
    @PostMapping(value = "/updateUser")
    public String updateUser(TUser user){
        userService.updateUser(user);
        return "以fastmybatis方式"+"更新成功";
    }

    /**
    * @description:更新用户的某些属性字段,以Map传入
    * @author:MuJiuTian
    * @createDate: 2019/6/8 15:03
    */
    @PostMapping(value = "/updatePartUser")
    public String updatePartUser(int id){
        userService.updateUser(CreateDataUtil.getuserForMap(id));
        return "以fastmybatis方式"+"更新用户局部成功";
    }

    /**
    * @description:查找某个用户
    * @author:MuJiuTian
    * @createDate: 2019/6/8 14:25
    */
    @GetMapping(value = "/getUser")
    public String getUser(int id){
        TUser tUser = userService.getUser(id);
        return "以fastmybatis方式获取对象数据:"+tUser.toString();
    }

    /**
    * @description:分页获取用户列表
    * @author:MuJiuTian
    * @createDate: 2019/6/8 14:25
    */
    @GetMapping(value = "/getPageUsers")
    public String getPageUsers(int pageIndex,int pageSize){
        Map map = userService.getPageResult(pageIndex,pageSize);
        return "以fastmybatis方式获取分页数据:"+map.toString();
    }

    /**
    * @description:更详细更简单的获取分页用户数据
    * @author:MuJiuTian
    * @createDate: 2019/6/8 15:29
    */
    @GetMapping(value = "/getEasyPageUsers")
    public String getEasyPageUsers(int pageIndex,int pageSize){
        PageInfo pageInfo = userService.getPageUsers(pageIndex,pageSize);
        return "获取更相信的数据成功";
    }

    /**
     * @description:以id排序获取用户
     * @author:MuJiuTian
     * @createDate: 2019/6/8 17:27
     */
    @GetMapping(value = "/getUsersForOrder")
    public String getUsersForOrder(){
        return userService.getUsersForOrder().toString();
    }
}
import com.example.fastmybatis.service.TUserService;
import com.example.fastmybatis.util.CreateDataUtil;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @Description:以原始mybatis方式CRUD操作数据库,测试fastmybatis框架是否兼容mybatis
* @Author:Mujiutian
* @CreateDate:2019/6/8 12:09
* @UpdateUser:
*/
@RestController
@RequestMapping(value = "/user/mybatis")
public class User2Controller {

   @Autowired
   @Qualifier("userService2")
   TUserService userService;

   @PostMapping(value = "/addUser")
   public String addUser(){
       userService.addUser(CreateDataUtil.getUser());
       return "fastmybatis框架使用mybatis方式:"+"创建数据成功";
   }
   @Delete(value = "/deleteUser")
   public String deleteUser(int id){
       userService.deleteUser(id);
       return "fastmybatis框架使用mybatis方式:"+"删除数据成功";
   }

   @PostMapping(value = "/updateUser")
   public String updateUser(int id){
       userService.updateUser(CreateDataUtil.getuserForMap(id));
       return "fastmybatis框架使用mybatis方式:"+"更新数据成功";
   }

   @GetMapping(value = "/getUser")
   public String getUser(int id){
       userService.getUser(id);
       return "fastmybatis框架使用mybatis方式:"+"获取数据成功";
   }

   @GetMapping(value = "/getPageUsers")
   public String getPageUsers(){
       return "mybatis的分页查询自己写吧:";
   }

    /**
     * @description:更详细更简单的获取分页用户数据
     * @author:MuJiuTian
     * @createDate: 2019/6/8 15:29
     */
    @GetMapping(value = "/getEasyPageUsers")
    public String getEasyPageUsers(int pageIndex,int pageSize){
        return "mybatis的分页查询自己写吧";
    }

    /**
     * @description:以id排序获取用户
     * @author:MuJiuTian
     * @createDate: 2019/6/8 17:27
     */
    @GetMapping(value = "/getUsersForOrder")
    public String getUsersForOrder(){
        return userService.getUsersForOrder().toString();
    }

}

8、Service层

两种框架共同写一样的功能,接口一样,实现类不同

import com.example.fastmybatis.entity.TUser;
import com.gitee.fastmybatis.core.PageInfo;

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

public interface TUserService {

    int addUser(TUser user);

    int deleteUser(int id);

    int updateUser(TUser user);

    int updateUser(Map user);

    TUser getUser(int id);

    int addUsers(List users);

    Map getPageResult(int pageIndex,int pageSize);

    PageInfo getPageUsers(int pageIndex,int pageSize);
    
    //排序获取用户
    List getUsersForOrder();
}
import com.example.fastmybatis.entity.TUser;
import com.example.fastmybatis.dao.TUserMapper;
import com.example.fastmybatis.service.TUserService;
import com.gitee.fastmybatis.core.PageInfo;
import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.util.MapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service("userService")
public class TUserServiceImpl implements TUserService {
    @Autowired
    TUserMapper tUserMapper;


    @Override
    public int addUser(TUser user) {
        tUserMapper.save(user);
        return 0;
    }

    @Override
    public int deleteUser(int id) {
        Query query = new Query();
        query.eq("id",id);
        return tUserMapper.deleteByQuery(query);
    }

    @Override
    public int updateUser(TUser user) {
        return tUserMapper.update(user);
    }

    @Override
    public int updateUser(Map user) {
        Query query = new Query();
        query.eq("id",Integer.valueOf(user.get("id").toString()));
        return tUserMapper.updateByMap(user,query);
    }

    @Override
    public TUser getUser(int id) {
        Query query = new Query();
        query.eq("id",id);
        TUser user = tUserMapper.getByQuery(query);
        return user;
    }

    @Override
    public int addUsers(List users) {
        return tUserMapper.saveBatch(users);
    }

    @Override
    public Map getPageResult(int pageIndex,int pageSize) {

        Map map = new HashMap<>();
        Query query            = new Query();
        query.page(pageIndex,pageSize);

        List users = tUserMapper.list(query);
        long total        = tUserMapper.getCount(query);

        map.put("list",users);
        map.put("total",total);
        return map;
    }

    @Override
    public PageInfo getPageUsers(int pageIndex,int pageSize) {

        Query query            = new Query();
        query.page(pageIndex,pageSize);

        return MapperUtil.query(tUserMapper,query);
    }

    @Override
    public List getUsersForOrder() {
       Query query = new Query();
       query.orderby("id", Sort.DESC);
       query.eq("isdel",0); //条件isdel==0
       return tUserMapper.list(query);
    }
}
import com.example.fastmybatis.dao.TUserMapper;
import com.example.fastmybatis.entity.TUser;
import com.example.fastmybatis.service.TUserService;
import com.gitee.fastmybatis.core.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service(value = "userService2")
public class TUserService2Impl implements TUserService {

    @Autowired
    TUserMapper userMapper;
    @Override
    public int addUser(TUser user) {
        return userMapper.addUserForMybatis(user);
    }

    @Override
    public int deleteUser(int id) {
        return userMapper.deleteUserForMybatis(id);
    }

    @Override
    public int updateUser(TUser user) {
        return userMapper.updateUserForMybatis(user);
    }

    @Override
    public int updateUser(Map user) {
        return userMapper.updateUserForMybatis(user);
    }

    @Override
    public TUser getUser(int id) {
        return userMapper.getUserForMybatis(id);
    }

    @Override
    public int addUsers(List users) {
        return 0;
    }

    @Override
    public Map getPageResult(int pageIndex, int pageSize) {
        return null;
    }

    @Override
    public PageInfo getPageUsers(int pageIndex, int pageSize) {
        return null;
    }
    
    @Override
    public List getUsersForOrder() {
        return userMapper.getUsersForOrder();
    }
}

实现类中就可以看到fastmybatis的代码量就少多了,毕竟都被封装好了

9、Dao层

该文件夹必须是dao,不能写成mapper,不然获取不到dao层里面的bean,可能是fastmybatis有限制

import com.example.fastmybatis.entity.TUser;
import com.example.fastmybatis.dao.provider.TUserSqlProvider;
import com.gitee.fastmybatis.core.mapper.CrudMapper;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;

import java.util.Map;

public interface TUserMapper extends CrudMapper {


    //mybatis有两种方式操作数据库,一个是注解,另外一个是xml文件
    //此次测试我们全部使用注解的形式,方法后面接的..ForMybatis都是以mybatis方式测试的
    @Insert({
            "insert into t_user(username,state,isdel,remark,add_time,money,left_money)",
            " values(#{username},#{state},#{isdel},#{remark},#{addTime},#{money},#{leftMoney})"
    })
    int addUserForMybatis(TUser user);


    @Delete({
            "delete from t_user where id = #{id}"
    })
    int deleteUserForMybatis(@Param("id") int id);


    int updateUserForMybatis(TUser user);

    @UpdateProvider(type = TUserSqlProvider.class,method = "updateUser")
    int updateUserForMybatis(Map user);

    @Select({
            "select id,username,state,isdel,remark,add_time,money,left_money from t_user where id = #{id}"
    })
    @Results({
            @Result(column = "id",jdbcType = JdbcType.INTEGER,property = "id"),
            @Result(column = "username",jdbcType = JdbcType.VARCHAR,property = "id"),
            @Result(column = "state",jdbcType = JdbcType.INTEGER,property = "id"),
            @Result(column = "isdel",jdbcType = JdbcType.INTEGER,property = "id"),
            @Result(column = "remark",jdbcType = JdbcType.LONGNVARCHAR,property = "id"),
            @Result(column = "add_time",jdbcType = JdbcType.DATE,property = "id"),
            @Result(column = "money",jdbcType = JdbcType.DECIMAL,property = "id"),
            @Result(column = "left_money",jdbcType = JdbcType.FLOAT,property = "id")
    }
    )
    TUser getUserForMybatis(@Param("id") int id);

    @SelectProvider(type = TUserSqlProvider.class,method = "getOrderUsers")
    List getUsersForOrder();
}
import com.example.fastmybatis.entity.TUser;
import org.apache.ibatis.jdbc.SQL;

import java.util.Map;

public class TUserSqlProvider {

    /**
    * @description:更新用户对象
    * @author:MuJiuTian
    * @createDate: 2019/6/8 13:50
    */
    public String updateUser(Map user){
        SQL sql = new SQL();
        sql.UPDATE("t_user");
        if (user.get("username") != null && user.get("username").toString() != ""){
            sql.SET("username=#{username,jdbcType=VARCHAR}");
        }
        if (user.get("remark") != null && user.get("remark").toString() != ""){
            sql.SET("remark=#{remark}");
        }
        if (user.get("state") != null){
            sql.SET("state=#{state}");
        }
        if (user.get("addTime") != null){
            sql.SET("add_time=#{addTime}");
        }
        if (user.get("money") != null){
            sql.SET("money=#{money}");
        }
        if (user.get("left_money") != null){
            sql.SET("left_money=#{leftMoney}");
        }
        sql.WHERE("id = #{id}");
        return sql.toString();
    }

    /**
    * @description:此方法针对添加user对象的时候,防止有字段为null情况
    * @author:MuJiuTian
    * @createDate: 2019/6/8 13:49
    */
    public String insertUser(TUser user){
        SQL sql = new SQL();
        sql.INSERT_INTO("t_user");
        if (user.getUsername() != null && user.getUsername() !=""){
            sql.VALUES("username","#{username,jdbcType=VARCHAR}");
        }
        //下面的if等我就不写了,参考上面的update就可以
        return sql.toString();
    }
    /**
    * @description:高级查询
    * @author:MuJiuTian
    * @createDate: 2019/6/8 16:59
    */
    public String getOrderUsers(Map map){
        SQL sql = new SQL();
        sql.SELECT("id,username,state");
        sql.FROM("t_user");
        sql.WHERE("isdel = 0");
        sql.ORDER_BY("id");
        return sql.toString();
    }
}

这样,我们就可以成功了,官网虽然有demo,但是是直接从Controoler到dao层或者直接测试类里面写的,正常开发还是需要service,毕竟事务需要回滚!

这个demo教你怎么使用mybatis全注解对数据CRUD、排序等,同时fastmybatis更简洁的写代码!

 

 

 

转载于:https://my.oschina.net/mdxlcj/blog/3059687

你可能感兴趣的:(崛起于Springboot2.X之整合FastMybatis、Mybatis精装版(44))