介绍:FastMybatis是一个比mybatis-plus更加简单的框架,没有复杂sql时xml也不需要编写,而且兼容mybatis的操作方式,所以接下来该博客讲解的Springboot集成fastmybatis框架,以及mybatis全注解的使用,90%开发没用过的代码风格,
项目代码:点击
fastmybatis开发文档:fastmybatis文档
前提:@Autowired、@Qualifier、@Service(value="") 请先明白这几个注解的区别,代码会用到。
0、容易出Bug的点
1.1、dao层对应的文件名TUserMapper.java 必须和resource/mybatis/mapper下面的
TUserMapper.xml文件名一致。
1.2、fastMybatis的xml中的namepace不需要写,resultMap是嵌套在框架内部,不用改成具
体实体类。
1.3、实体类必须要有主键的注解,不然会报错。
1.4、千万不要在启动类加MapperScan() 的扫描,这个很重要,不然会扫描不到fastmybatis封
装的方法。
目录结构图:
UserControllers以fastmybatis框架写的增、删、改、差、分页、排序,开发中涉及到都写全了。
User2Controoler以mybatis方式写的增、删、改、差、排序等(分页自己网上找一下吧)
1、创建工程
2、pom文件
<dependency> <groupId>net.oschina.durcframework</groupId> <artifactId>fastmybatis-spring-boot-starter</artifactId> <version>1.7.3</version> </dependency>
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='用户表';
4、配置文件
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
5、mybatisConfig.xml配置
放在文件下,不懂看目录图
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- 全局映射器启用缓存 --> <setting name="cacheEnabled" value="true" /> <!-- 查询时,关闭关联对象即时加载以提高性能 --> <setting name="lazyLoadingEnabled" value="true" /> <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true" /> <!-- 允许使用列标签代替列名 --> <setting name="useColumnLabel" value="true" /> <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 --> <setting name="useGeneratedKeys" value="false" /> <!-- 对于批量更新操作缓存SQL以提高性能:BATCH --> <setting name="defaultExecutorType" value="SIMPLE" /> <!-- 超时设置 --> <setting name="defaultStatementTimeout" value="25000" /> <setting name="logImpl" value="LOG4J" /> </settings> </configuration>
6、实体类TUser
如果使用fastmybatis方式,那么实体类一定要有主键@Id什么的,不然会报错pk.fullType错误,谨记!
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; }
7、工具类CreateDataUtil
public class CreateDataUtil { //方便下面添加用戶測試,num是创造多少个user实体类对象 public static List<TUser> getUsers(int num){ List<TUser> tUsers = new ArrayList<>(); for (int i = 0;i<num;i++){ byte a = 1; TUser user = new TUser(); user.setAddTime(new Date()); user.setIsdel(false); user.setMoney(new BigDecimal(12.00)); user.setAddTime(new Date()); user.setRemark("测试"); user.setState(a); user.setLeftMoney(1f); user.setUsername("mujiutian测试"+ UUID.randomUUID().toString().split("-")[1]); tUsers.add(user); } return tUsers; } public static TUser getUser(){ byte a = 1; TUser user = new TUser(); user.setAddTime(new Date()); user.setIsdel(false); user.setMoney(new BigDecimal(14.00)); user.setAddTime(new Date()); user.setRemark("添加用户"); user.setState(a); user.setLeftMoney(2f); user.setUsername("mujiutian测试"+ UUID.randomUUID().toString().split("-")[1]); return user; } /** * @description:更新用户对象的时候,我们只部分更新字段,但是实体类中像int类型,你不传值它会有一个默认值 * 所以我们用Map代替实体类对象进行局部update * @author:MuJiuTian * @createDate: 2019/6/8 14:27 */ public static Map<String,Object> getuserForMap(int id){ Map<String,Object> map = new HashMap<>(); map.put("username","更新后的大魔王"); map.put("id",id); return map; } }
改工具类只为了测试创建数据而已,调用接口的时候直接使用这些对象数据就可以了,省的在postman等工具编写参数了。
8、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<String,Object> 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<TUser> 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(); } }
9、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<String,Object> user); TUser getUser(int id); int addUsers(List<TUser> users); Map<String,Object> getPageResult(int pageIndex,int pageSize); PageInfo<TUser> getPageUsers(int pageIndex,int pageSize); //排序获取用户 List<TUser> 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<String, Object> 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<TUser> users) { return tUserMapper.saveBatch(users); } @Override public Map<String, Object> getPageResult(int pageIndex,int pageSize) { Map<String,Object> map = new HashMap<>(); Query query = new Query(); query.page(pageIndex,pageSize); List<TUser> users = tUserMapper.list(query); long total = tUserMapper.getCount(query); map.put("list",users); map.put("total",total); return map; } @Override public PageInfo<TUser> getPageUsers(int pageIndex,int pageSize) { Query query = new Query(); query.page(pageIndex,pageSize); return MapperUtil.query(tUserMapper,query); } @Override public List<TUser> 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<String, Object> user) { return userMapper.updateUserForMybatis(user); } @Override public TUser getUser(int id) { return userMapper.getUserForMybatis(id); } @Override public int addUsers(List<TUser> users) { return 0; } @Override public Map<String, Object> getPageResult(int pageIndex, int pageSize) { return null; } @Override public PageInfo<TUser> getPageUsers(int pageIndex, int pageSize) { return null; } @Override public List<TUser> getUsersForOrder() { return userMapper.getUsersForOrder(); } }
实现类中就可以看到fastmybatis的代码量就少多了,毕竟都被封装好了
10、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<TUser,Integer> { //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<String,Object> 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<TUser> 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<String,Object> 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<String,Object> 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更简洁的写代码!
来源:oschina
链接:https://my.oschina.net/u/3209213/blog/3059687