JAVA: Fastmybatis simplified development framework

1 Introduction

fastmybatis is a mybatis development framework, its purpose is: simple, fast and effective.
Quick start with zero configuration
CRUD operations can be completed without writing xml files
Support mysql, sqlserver, oracle, postgresql, sqlite
Support custom sql, sql statements can be written in annotations or xml
Support integration with spring-boot, rely on the starter to
easily Quantitative, non-invasive, it is an extension of the official mybatis
Document introduction address: https://durcframework.gitee.io/fastmybatis/#/?t=1670849880047
GitHub address: https://gitee.com/durcframework/fastmybatis

2. Maven reference

Create a new springboot project and add fastmybatis-spring-boot-starter in pom.xml

<dependency>
    <groupId>net.oschina.durcframework</groupId>
    <artifactId>fastmybatis-spring-boot-starter</artifactId>
    <version>最新版本(见changelog.md)</version>
</dependency>

3. Detailed explanation of Mapper

Mapper in fastmybatis provides a series of methods for adding, deleting, modifying and checking to meet daily needs. The complete method description is shown in the following table:

method illustrate
E getByColumn(String column, Object value) Query a record by field
E getById(I id) Query by primary key
E getByQuery(Query query) Find a single record by condition
E getBySpecifiedColumns(List columns, Query query) Query a single piece of data and return the specified field
T getBySpecifiedColumns(List columns, Query query, Class clazz) Query a single piece of data to return the specified field and convert it to the specified class
T getColumnValue(String column, Query query, Class clazz) Query the value of a field in a row
long getCount(Query query) Query the total number of records
List list(Query query) query result set
List listByArray(String column, Object[] values) Query result set based on multiple field values
List listByCollection(String column, Collection<?> values) Query the result set based on multiple values ​​of the field
List listByColumn(String column, Object value) Query result set by field
List listByIds(Collection ids) Query based on multiple primary keys
List listBySpecifiedColumns(List columns, Query query) The query returns the specified column and returns the entity class collection
List listBySpecifiedColumns(List columns, Query query, Class clazz) The query returns the specified column, and returns the specified class collection
List listColumnValues(String column, Query query, Class clazz) Query the specified column and return the specified column set
PageInfo page(Query query) Paging query
PageInfo page(Query query, Function<E, R> converter) Query the result set, and convert the records in the result set, and convert each row
PageInfo page(Query query, Supplier target, Consumer format) Query the result set, and transform the records in the result set, and perform additional processing on the records
PageInfo page(Query query, Supplier target) Query the result set, and convert the records in the result set
PageInfo pageAndConvert(Query query, Function<List, List> converter) Query the result set, convert the records in the result set, and convert the list
PageInfo pageBySpecifiedColumns(List columns, Query query, Class clazz) The query returns the specified column and returns the paged data
PageEasyui pageEasyui(Query query) The query returns the easyui result set
PageEasyui pageEasyui(Query query, Class clazz) The query returns the easyui result set and converts the records in the result set
E forceById(I id) Force query based on primary key query, ignoring tombstone fields
int save(E entity) save, save all fields
int saveBatch(Collection entitys) Batch save
int saveIgnoreNull(E entity) Save, ignore null fields
int saveMultiSet(Collection entitys) Batch saving, compatible with more database versions, ignoring duplicate rows, this method uses union to insert in batches
int saveOrUpdate(E entity) Save or modify, execute UPDATE when there are records in the database, otherwise execute INSERT
int saveOrUpdateIgnoreNull(E entity) Save or modify, ignore null fields, execute UPDATE when there are records in the database, otherwise execute INSERT
int saveUnique(Collection entitys) Save in batches, remove duplicate rows, judge duplicate data by whether the object is relative, the entity class needs to implement the equals method
int saveUnique(Collection entitys, Comparator comparator) Save in batches, remove duplicate rows, and specify comparator judgment
int updateByQuery(E entity, Query query) 根据条件更新
int updateIgnoreNull(E entity) 更新,忽略null字段
int updateByMap(Map<String, Object> map, Query query) 根据条件更新,map中的数据转化成update语句set部分,key为数据库字段名
int delete(E entity) 删除,在有逻辑删除字段的情况下,做UPDATE操作
int deleteByColumn(String column, Object value) 根据指定字段值删除,在有逻辑删除字段的情况下,做UPDATE操作
int deleteById(I id) 根据id删除,在有逻辑删除字段的情况下,做UPDATE操作
int deleteByIds(Collection ids) 根据多个主键id删除,在有逻辑删除字段的情况下,做UPDATE操作
int deleteByQuery(Query query) 根据条件删除,在有逻辑删除字段的情况下,做UPDATE操作
int forceDelete(E entity) 强制删除(底层根据id删除),忽略逻辑删除字段,执行DELETE语句
int forceDeleteById(I id) 根据id强制删除,忽略逻辑删除字段,执行DELETE语句
int forceDeleteByQuery(Query query) 根据条件强制删除,忽略逻辑删除字段,执行DELETE语句
Map<K, E> getMap(Query query, Function<E, K> keyGetter) 查询结果并转换成Map对象
<T extends TreeNode<T, I>> List listTreeData(Query query, I rootId) 查询列表并将结果转换成树结构

4、Mapper

创建一个mapper接口,继承CrudMapper,可以获取mapper所有支持的接口函数。

public interface TTagMapper extends CrudMapper<Tag/*实体类*/,Integer/*主键类型*/> {
}

也可以通过自定义SQL,来实现mapper接口

 public interface TTagMapper extends CrudMapper<Tag/*实体类*/,Integer/*主键类型*/> {

    @Update("update blog_tag set username = #{username} where id = #{id}")
    int updateById(@Param("id") int id, @Param("username") String username);
}

指定外部模板,默认template-classpath的值为/fastmybatis/tpl/当前路径,也可以通过Application配置来指定具体的路径:

mybatis:
  ignoreLogicDeleteWithAssociatio: true
  mapper-locations: classpath*:/mapper/**/*.xml

5、Service

创建一个Service实现IService接口服务,添加@Service注解

@Service
public class TagService implements IService<Tag/*实体类*/,Integer/*主键类型*/> {
}

6、实体类

实体类注解,通过@Table来指定表名,指定主键。

@Data
@Table(name="blog_tag", pk = @Pk(name = "id", strategy = PkStrategy.INCREMENT))
public class Tag implements Serializable {
    private static final long serialVersionUID = 1L;

    private  Integer id;

    /**
     * 标题
     */
    private String name;
    /**
     * 标题icon
     */
    private String iconUrl;

    /**
     * create_time
     */
    private Date createTime;

    /**
     * update_time
     */
    private Date updateTime;
}

6.1 主键自增

适用于:mysql自增主键、sqlserver自增主键、oracle(触发器)

数据库主键设置自增后,这样设置:

// strategy = PkStrategy.INCREMENT 自增策略
@Table(name = "t_user", pk = @Pk(name = "id", strategy = PkStrategy.INCREMENT))
public class TUser {
}

这样在做insert后,id会自动填充自增后的值。

6.2 主键使用sequence(oracle)

适用于oracle表序列

– 创建表sequence,名字为t_user_seq
create sequence t_user_seq start with 1 increment by 1;
使用如下注解:

@Table(name = "t_user", pk = @Pk(name = "id", sequenceName = "t_user_seq"))
public class TUser {
}

6.3 主键使用uuid

数据库主键是varchar类型,insert后自动填充uuid,并返回。

@Table(name = "log", pk = @Pk(name = "log_id", strategy = PkStrategy.UUID/*配置主键UUID*/))
public class Log {
    private String logId;
}

这样在做insert后,id字段会自动填充uuid。

注:uuid的生成方式是调用数据库底层实现,如MySql的实现方式为: SELECT UUID()

7、Controller

简化当前Service编写代码,同时通过Query来构建多种查询条件,通过@Condition注解来生成各种查询条件。

@RestController
@RequestMapping("blog")
public class TagController {
    @Autowired
    private TagService tagService;

    /**
     * 分页查询
     * @param param
     * @return
     */
    @GetMapping("/tag/page")
    public R page(TagParam param) {
        Query query = param.toQuery();

        PageInfo<Tag> pageInfo = tagService.page(query);
        return R.ok().put("pageInfo", pageInfo);
    }

    /**
     * 保存
     * @param tag
     * @return
     */
    @GetMapping("/tag/save")
    public R save(Tag tag) {
        tagService.saveIgnoreNull(tag);
        return new R().ok().put("id", tag.getId());
    }


    /**
     * 更新
     * @param tag
     * @return
     */
    @GetMapping("/user/update")
    public R update(Tag tag) {
        tagService.updateIgnoreNull(tag);
        return R.ok();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/tag/delete")
    public R delete(Integer id) {
        tagService.deleteById(id);
        return R.ok();
    }
}

分页查询是经常使用的,Fastmybatis 自带了分页查询,可以通过param请求参数来定义传输分页和返回PageInfo包含分页的数据。

@Data
public class TagParam extends PageParam {
    /**
     * 标题
     */
    private String name;
}

在这里插入图片描述
还有更多的应用等着我们去发掘。。。。。。。。

Guess you like

Origin blog.csdn.net/lishangke/article/details/129613214