4 Star 8 Fork 1

小白/custom-db-orm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

custom-springboot-starter

简介

简易ORM操作工具,纯原生JDBC+阿里的Druid连接池,集成条件构造器,使用简单,一看就会,一用就爽,让增删改查变得更容易,支持ActiveRecord以及链式查询

说明:

  • com.custom.action.core.JdbcDao,该类提供了多种增删改查方法以供用户自定义使用,使用时只需要在service或controller注入该对象即可,只需要编写部分的条件sql ,即可完成单表的大部分增删改查操作。
  • 只需要创建实体类,并添加上自定义的几个注解,即可生成对应的表结构。
  • 暂时只支持Mysql
  • 支持可配置的表关联查询以及逻辑删除,sql语句打印输出,下划线转驼峰等功能。
  • 该工具已完成springboot的自动配置,在springboot项目中引入该依赖即可,无需另外配置,轻松便捷。

安装依赖

SpringBoot-自动配置
         <dependency>
            <groupId>com.xb-custom</groupId>
            <artifactId>custom-springboot-starter</artifactId>
            <version>1.0.0</version>
            <!-- 或最新版本  -->
        </dependency>

springboot方式 -- 配置数据源

SpringBoot项目配置数据源:因dataSource类为本工具自定义,所以在application.yml(properties)中进行如下基本配置即可,mysql 驱动默认为mysql8.0--->com.mysql.cj.jdbc.Driver(配置文件中可不写)

custom.db.datasource.url=jdbc:mysql://127.0.0.1:3306/hos?characterEncoding=utf-8&allowMultiQueries=true&autoreconnect=true&serverTimezone=UTC
custom.db.datasource.username=root
custom.db.datasource.password=123456

纯依赖-手动配置

         <dependency>
            <groupId>com.xb-custom</groupId>
            <artifactId>custom-db-action</artifactId>
            <version>1.0.0</version>
        </dependency>

手动方式 -- 配置数据源

		// 数据库连接配置
        DbDataSource dbDataSource = new DbDataSource();
        dbDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/hos?characterEncoding=utf-8&allowMultiQueries=true&autoreconnect=true&serverTimezone=UTC");
        dbDataSource.setUsername("root");
        dbDataSource.setPassword("123456");
        // Driver不用填,默认mysql8.0

        // 全局配置
        DbGlobalConfig globalConfig = new DbGlobalConfig();

        // 策略配置
        DbCustomStrategy dbCustomStrategy = new DbCustomStrategy();
        // sql打印开关
        dbCustomStrategy.setSqlOutPrinting(true);
        // sql打印时, true为可执行的sql(即参数?已经替换为真实的值), 默认false
        dbCustomStrategy.setSqlOutPrintExecute(true);
        // 是否下划线转驼峰?
        dbCustomStrategy.setUnderlineToCamel(true);

        // 逻辑删除的字段(表字段)
        dbCustomStrategy.setDbFieldDeleteLogic("state");
        // 逻辑删除的标识值
        dbCustomStrategy.setDeleteLogicValue(1);
        // 未逻辑删除的标识值
        dbCustomStrategy.setNotDeleteLogicValue(0);

        globalConfig.setStrategy(dbCustomStrategy);

使用说明

import com.custom.action.core.JdbcDao;

// 注入JdbcDao,即可使用
@Autowired
private JdbcDao jdbcDao;
  1. 该工具提供大量的增删改查方法API
  • 一般查询

    查询多条记录: 例1(and a.name = ?, "张三"),例2 (and a.name = "张三") 
    public <T> List<T> selectList(Class<T> t, String condition, Object... params);


    根据多个主键查询多条记录
    public <T> List<T> selectListByKeys(Class<T> t, Collection<? extends Serializable> keys);


    根据sql查询多条记录: 例(select * from table)
    public <T> List<T> selectListBySql(Class<T> t, String sql, Object... params);


    根据条件进行分页查询并排序: 例(and a.name = ?, 1, 10, "张三")
    public <T> DbPageRows<T> selectPageRows(Class<T> t, String condition, int pageIndex, int pageSize, Object... params);


    根据主键查询一条记录: 例 (25)
    public <T> T selectOneByKey(Class<T> t, Object key);

    纯sql查询一条记录: 例(select * from table where age = ?, 25)
    public <T> T selectOneBySql(Class<T> t, String sql, Object... params);

    纯sql查询单个值: 例(select name from table where age = ?, 25)
    public Object selectObjBySql(String sql, Object... params);

    根据条件查询一条记录
    public <T> T selectOneByCondition(Class<T> t, String condition, Object... params);
  • 条件构造查询**(**与mybatis-plus的条件构造器相差无几)

    selectPageRows(查询分页)

    selectList(查询多条)

    selectCount(查询记录数)

    selectOne(查询单条记录)

    selectObj(查询单列字段,并且只有一个值,若有多个,只返回第一个满足条件的值)

    selectObjs(同上,但允许会返回多个值)

  public <T> DbPageRows<T> selectPageRows(ConditionWrapper<T> wrapper);
  public <T> List<T> selectList(ConditionWrapper<T> wrapper);
  public <T> T selectOne(ConditionWrapper<T> wrapper);
  public <T> long selectCount(ConditionWrapper<T> wrapper);
  public <T> Object selectObj(ConditionWrapper<T> wrapper);
  public <T> List<Object> selectObjs(ConditionWrapper<T> wrapper);

使用示例

  1: 一般字段构造
      
      DefaultConditionWrapper<Student> wrapper = new DefaultConditionWrapper<>(Student.class);
      wrapper.eq("name", "张三").select("id", "name", "age").pageParams(1, 10);
      DbPageRows<Student> dbPageRows = jdbcDao.selectPageRows(wrapper);
  
  2: lambda表达式构造
      
     	LambdaConditionWrapper<Student> wrapper = new LambdaConditionWrapper<>(Student.class);
     	wrapper.eq(Student::getName, "张三")
          .select(Student::getName, Student::getId, Student::getAge)
          .pageParams(1, 10);
      DbPageRows<Student> dbPageRows = jdbcDao.selectPageRows(wrapper);
  
  3: 使用静态方法实例化
      DbPageRows<ChildStudent> dbPageRows = jdbcDao.selectPageRows(Conditions.lambdaQuery(Student.class)
                  .eq(Student::getName, "张三")
                  .select(Student::getName, Student::getId, Student::getAge)
                  .pageParams(1, 10)
     );
  
  额外说明: 
      1. 使用onlyPrimary()方法时, 可使本次查询只查询主表数据.
      2. 使用select方法时, 可使用部分sql函数(仅支持sum/max/min/ifnull/count/avg),例如:
      List<Student> students = jdbcDao.selectList(Conditions.lambdaQuery(Student.class)
                  .eq(Student::getName, "张三")
                  .between(Student::getAge, 20, 25)
                  .select(Student::getAge)
                  .select(x -> x.sum(Student::getAge, Student::getSumAge))
                  .groupBy(Student::getAge)
          );
  • 实时同步查询(一对一、一对多)
/**
 * 同步查询-查询多条记录
 */
<T> List<T> selectList(SyncQueryWrapper<T> wrapper);

/**
 * 同步查询-查询单条记录
 */
<T> T selectOne(SyncQueryWrapper<T> wrapper);

/**
 * 同步查询-分页
 */
<T> DbPageRows<T> selectPage(SyncQueryWrapper<T> wrapper);

使用示例

// 查询单个对象
Student student = jdbcDao.selectOne(Conditions.syncQuery(Student.class)
                // student对象的查询(即主对象)
                .primaryEx(x -> x.eq(Student::getNickName, "siyecao"))
                // student对象中某个非持久化属性的查询(即一对一、一对多)
                // t 即是查询后的student对象,作为预判断提前使用
                .property(Student::setModelList, t -> t.getModelList() == null,
                        Conditions.lambdaQuery(Street.class).in(Street::getId, 5012, 5013, 5014, 5015))
                .property(Student::setProvince, t -> t.getProvince() == null,
                        t -> Conditions.lambdaQuery(Province.class).in(t.getProId() != null, Province::getId, t.getProId()))
        );

Province province = student.getProvince();
// 查询多条主对象
List<City> cityList = jdbcDao.selectList(Conditions.syncQuery(City.class)
                                         .primaryEx(x -> x.eq(City::getProvinceId, province.getId()))
                                         .property(City::setLocationList, t -> Conditions.lambdaQuery(Location.class).in(Location::getCityId, t.getId()))
                                        );
province.setCityList(cityList);
  • 删除
    根据主键删除一条记录
    public <T> int deleteByKey(Class<T> t, Object key);

    根据主键删除多条记录
    public <T> int deleteBatchKeys(Class<T> t, Collection<? extends Serializable> keys);

    根据条件删除记录
    public <T> int deleteByCondition(Class<T> t, String condition, Object... params);

    根据条件删除记录
    public <T> int deleteSelective(ConditionWrapper<T> wrapper);
  • 修改
    根据主键修改一条记录
    public <T> int updateByKey(T entity);

    根据条件修改一条记录(只修改entity中属性值 !=null 的字段)
    public <T> int updateByCondition(T entity, String condition, Object... params);

    根据sql set设置器修改n条记录
	public <T> int updateSelective(AbstractUpdateSet<T> updateSet);
  • 添加
    插入一条记录
    public <T> long insert(T entity);

    插入多条记录
    public <T> int insertBatch(List<T> entityList);
  • 公共方法
  保存一条记录(根据主键添加或修改)
  public <T> int save(T entity);
  
  执行一条sql(增删改)
  public <T> int executeSql(String sql, Object... params);
  
  删除表
  public void dropTables(Class<?>... arr);
  
  创建表
  public void createTables(Class<?>... arr);
  • 事务执行
  事务执行方法
  public void execTrans(TransactionExecutor executor);

使用示例

jdbcDao.execTrans(() -> {
    // 逻辑写在里面即可
    Employee employee = jdbcDao.selectByKey(Employee.class, 10);
    employee.setEmpName("zhangsan");
    jdbcDao.updateByKey(employee);
    int a = 1 / 0;
    employee.setEmpName("lisi");
    jdbcDao.updateByKey(employee);
});
  • 实体注解介绍

主键注解:@DbKey(仅可标注在java属性上)

注解属性 说明
value 表主键字段,若不填写,则默认与java属性一致,当策略中驼峰转下划线为true时,解析时会自动转下划线
strategy 提供三种主键策略:AUTO为自增. UUID为系统UUID,添加时会自动生成. INPUT则需要自行输入主键值,默认AUTO
dbType 数据库对应字段类型:一共提供十多种类型供选择,为枚举属性,默认为DbType.DbInt
desc 字段说明

普通字段注解:@DbField(仅可标注在java属性上)

注解属性 说明
value 表主键字段,若不填写,则默认与java属性一致,当策略中驼峰转下划线为true时,解析时会自动转下划线
dataType 数据库对应字段类型:一共提供十多种类型供选择,为枚举属性,默认为DbType.DbVarchar
desc 字段说明
isNull 是否允许为空,该属性仅在创建表时用到
exist 是否存在该表字段,作用与DbNotField一致
fillStrategy 自动填充策略,在参数为实体时的插入或者修改(逻辑删除)时,自动填充指定字段的值

关联表注解1:@DbRelated(仅可标注在java属性上)

注解属性 说明
joinTable 要关联的表,例如:teacher
joinAlias 关联表的别名,例如:tea
condition 关联条件,例如:a.tea_id = tea.id
joinStyle 关联方式,可选:inner join,left join,right join
field 注入的字段,也就是要查询的表字段(teacher_name)

关联表注解2:@DbJoinTables(仅可标注在java类上)

注解 说明
@DbJoinTable @DbJoinTables中内部注解,该注解仅用于配置表关联条件,例如:left join teacher tea on a.tea_id = tea.id
@DbJoinField 配合@DbJoinTable一起使用,value值必须带上关联表的别名,例如:tea.teacher_name

表注解:@DbTable(仅可标注在java类上)

注解属性 说明
table 表名
alias 别名
desc 表说明
order 若存在动态数据源,则指定该值与dataSource中的order一致即可

非持久化字段注解:@DbNotField(标识在java属性上)

在实体中指定忽略的属性,该注解作用与@DbField.exist = false 一致,表示不属于表的字段。

若字段上同时标注了@DbField 或者 @DbKey 与此类注解,则此注解记为无效,

  • 注解使用示例
@Data
@DbJoinTables({
        @DbJoinTable("left join province pro on pro.id = a.pro_id"),
        @DbJoinTable("left join city cy on cy.id = a.city_id"),
})
@DbTable(table = "student")
public class Student {

    @DbKey(value = "id", strategy = KeyStrategy.AUTO, dbType = DbType.DbInt)
    private Integer id;

    @DbField
    private String name;

    @DbField("nick_code")
    private String nickName;
    
    @DbField
    private Integer areaId;

    @DbJoinField("pro.name")
    private String province;

    @DbJoinField("cy.name")
    private String city;
    
    @DbNotField
    private List<String> childrenList;
  1. 第二步,执行createTables方法即可
JdbcDao.createTables(Student.class);
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

简易ORM操作工具,低代码,操作简单,功能强大,上手快,纯原生JDBC+阿里的Druid连接池,集成Mybatis-Plus的条件构造器,在此之上添加了多表连接的条件构造,使增删改查变得更容易,支持动态一对一(一对多)查询,支持ActiveRecord以及链式查询。 展开 收起
README
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/openter/custom-db-orm.git
git@gitee.com:openter/custom-db-orm.git
openter
custom-db-orm
custom-db-orm
master

搜索帮助