4 Star 9 Fork 5

陈钇蒙 / jpaHelper

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

jpaHelper

介绍

本项目是基于spring-data-jpa的orm,主要特点是像mongodb一样使用sql数据库.

在敏捷开发中,最难以管理的业务关系是数据库的表结构,因为数据库表结构不可写成代码,无法使用版本管理工具进行迭代管理,每次新的需求来了以后,要使用各种手段修改各处的数据库表结构,开发数据库,测试数据库,正式数据库等等,而且要保证他们一致,否则上一个版本的代码运行在下一个版本的数据库上是会出现错误的.

传统关系型数据库,要修改表结构必须使用alter,create等语句。为了保证项目中测试数据库与正式数据库或其他数据库结构一致,有了flyway这种东西,但实际使用中依然不便。首先flyway以sql文件名版本号的形式来维护数据库版本,项目时间一长,flyway文件夹的sql文件数量会变得非常庞大,另外一点,两个开发者同时想要修改表结构时,极易产生版本冲突,两人可能在同一时间都提交了同一个版本号的sql文件,导致flyway执行出错,这种问题处理起来及其麻烦。另外如果一个开发人员本地代码的pojo类与数据库表字段对不上(已经被另外一个开发人员的flyway更新),执行指定字段的select或insert语句是会报错的,此时他只能等待另外一名开放人员将新版pojo类提交。

理想情况下,需求快速变化的敏捷开发应该使用mongodb这种文档性数据库,每个表(集合)的表结构都是动态的,可以插入任意结构的数据,本人另外一个项目mongoHelper就是为此而生的orm,如果能接受直接使用mongodb,可使用该项目: https://gitee.com/cym1102/mongoHelper

jpaHelper为mongoHelper的兄弟项目,旨在为关系型数据库提供近似mongodb的使用体验.即开发过程中完全不用关心数据库结构,在任意一个空白或是有结构的数据库中,在项目启动的瞬间都可以立刻构建出与pojo类对应的数据库结构,可以立即开始进行业务开发.除了查询sql语句的执行效果,已经完全不必打开数据库客户端对数据库结构进行管理了.

软件架构

本项目只适用于springBoot项目,项目也依赖springBoot相关库,springMVC项目无法使用,另外项目依赖了hutool提供的诸多Util工具,让代码更简洁。

安装教程

  1. 引入maven库
    <dependency>
        <groupId>cn.craccd</groupId>
        <artifactId>jpaHelper</artifactId>
        <version>0.3.2</version>
    </dependency>
  1. 在有@Configuration的类上添加注解
@ComponentScan("cn.cucc")
@Configuration
public class WebConfig {

}
  1. 在application.yml文件中加入如下配置
spring:
  datasource: #数据库配置(jpa会根据url协议自动判断数据库类型)
    url: jdbc:postgresql://xxx.xxx.xxx.xxx:5432/database
    username: postgres
    password: postgres
  jpa:
    properties:
      hibernate.globally_quoted_identifiers: true #对jpa sql关键字进行转义
      hibernate.globally_quoted_identifiers_skip_column_definitions: true #不要对字段类型进行转义
    hibernate: 
      ddl-auto: update #自动更新数据库表,如不需要自动更新数据库,则取消此参数

使用说明

1. 基本操作

本orm会在容器中注入一个对象JpaHelper,这个对象拥有诸多单表查询功能,如下

  • 按id删除:deleteById(String, Class<?>)
  • 按条件删除:deleteByQuery(ConditionAndWrapper, Class<?>)
  • 查询所有:findAll(Class)
  • 查询数量:findCount(Class<?>)
  • 根据id查询:findById(String, Class)
  • 根据条件查询:findListByQuery(ConditionAndWrapper, Class<?>)
  • 根据条件查询并分页:findPage(ConditionAndWrapper, Page, Class<?>)
  • 插入:insert(Object)
  • 插入或更新:insertOrUpdate(Object)
  • 根据id更新:updateById(Object)
  • 根据id更新全部字段:updateAllColumnById(Object)

这个JpaHelper能够完成所有查询任务,插入和更新操作能够自动判断pojo的类型操作对应表,查询操作根据传入的Class进行对应表操作,本orm所有数据库操作都基于JpaHelper的功能,不用像mybatis一样,每个表都要建立一套Mapper,xml,Service,model,大大减少数据层的代码量。可以将JpaHelper直接注入到controller层,简单的操作直接调用JpaHelper进行操作,不需要调用service层。

而复杂的查询需要使用ConditionAndWrapper,将JpaHelper注入service,可以在service成构建查询条件。

POJO类:

@Entity
public class User{
	@Id // 主键注解
	String id;
	@CreateTime // 自动插入创建时间戳的注解
	Long createTime;
	@UpdateTime // 自动插入更新时间戳的注解
	Long updateTime;
		
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public Long getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Long createTime) {
		this.createTime = createTime;
	}
	public Long getUpdateTime() {
		return updateTime;
	}
	public void setUpdateTime(Long updateTime) {
		this.updateTime = updateTime;
	}
}

注意: 本orm的事务放在了controller层, 即每一个请求是一个事务,如果一个请求会修改数据库,请在controller的方法上加@Transactional,在service层加@Transactional无效

2. 复杂查询功能

本orm的查询功能都在JpaHelper的findByQuery,findPage方法中.使用ConditionAndWrapper和ConditionOrWrapper对象作为sql的拼接对象

// 根据输入条件进行查询
public List<User> search(String word, Integer type) {
	ConditionAndWrapper conditionAndWrapper = new ConditionAndWrapper();

	if (StrUtil.isNotEmpty(word)) {
		conditionAndWrapper.and(new ConditionOrWrapper().like(User::getName, word).like(User::getPhone, word));
	}
	if (type != null) {
		conditionAndWrapper.eq(User::getType, type);
	}
		
	List<User> userList = jpaHelper.findListByQuery(conditionAndWrapper, User.class);

	return userList ;
}

以上代码组装了类似于select * from user where (name like '%xxx%' or phone like '%xxx%') and type = xxx的查询语句。

本项目不支持使用left join rigth join等连接查询,关系型数据库的连表查询能解决很多问题,但在大公司中已不再推荐使用,因为很难做数据库优化,数据量庞大时查询时间很慢而且很难进行优化。需要连表查询时,先查出对方id集,再使用in进行包含查询,可以很方便的走索引,而且分库的时候很容易修改。这样使用的话,实际是将关系型数据库用成了近似文档型数据库,表之间不再产生关联。

基于以上理念,本orm还提供了一些小功能用于完善这种多次连接查询,在jpaHelper中有以下方法

  • 只查出表的id作为List返回:findIdsByQuery(ConditionAndWrapper conditionAndWrapper, Class<?> clazz)
  • 只查出表的某个字段作为List返回:findPropertiesByQuery(ConditionAndWrapper conditionAndWrapper, Class<?> documentClass, String property, Class propertyClass)

用法示例:

// 查出订单下的所有商品(OrderProduct.class为订单商品对照表)
public List<Product> getProductList(String orderId) {
	List<String> productIds = jpaHelper.findPropertiesByQuery(new ConditionAndWrapper().eq(OrderProduct::getOrderId, orderId), OrderProduct.class,  OrderProduct::getProductId, String.class);
	return jpaHelper.findListByQuery(new ConditionAndWrapper().in(Product::getId, productIds), Product.class);
}


// 根据产品名查出所有订单
public PageResp<Order> search(PageReq pageReq, String keywords) {
	ConditionOrWrapper conditionOrWrapper = new ConditionOrWrapper();
		
	if (StrUtil.isNotEmpty(keywords)) {
			
	    List<String> productIds = jpaHelper.findIdsByQuery(new ConditionAndWrapper().like(Product::getName, keywords), Product.class);
	    List<String> orderIds = jpaHelper.findPropertiesByQuery(new ConditionAndWrapper().in(OrderProduct::getProductId, productIds), OrderProduct.class,  OrderProduct::getOrderId, String.class);
	
	    conditionOrWrapper.in(Order::getId, orderIds);
	}

	PageResp<Order> page = jpaHelper.findPage(conditionOrWrapper, pageReq, Order.class);
	return page;
}
3. 分页查询,

本orm提供一个PageResp类,包含total总记录数,pageSize每页记录数,pageNum起始页(从1开始), list结果列表四个属性,只要将包含pageNum和pageSize数据的PageReq对象传入findPage,即可查询出total,list的数据并自动返回到PageResp对象中。

public PageResp<User> search(PageReq pageReq, String word, Integer type) {
    ConditionAndWrapper conditionAndWrapper = new ConditionAndWrapper();

	if (StrUtil.isNotEmpty(word)) {
		conditionAndWrapper.and(new ConditionOrWrapper().like(User::getName", word).like(User::getPhone, word));
	}
	if (type != null) {
		conditionAndWrapper.eq(User::getType, type);
	}
	Sort sort = new Sort(User:getCreatTime, Direction.DESC);	
	PageResp<User> page = jpaHelper.findPage(conditionAndWrapper, sort, pageReq, User.class);

	return page;
}
木兰宽松许可证, 第1版 木兰宽松许可证, 第1版 2019年8月 http://license.coscl.org.cn/MulanPSL 您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第1版(“本许可证”)的如下条款的约束: 0. 定义 “软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。 “贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。 “法人实体”是指提交贡献的机构及其“关联实体”。 “关联实体”是指,对“本许可证”下的一方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。 “贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。 1. 授予版权许可 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。 2. 授予专利许可 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括仅因您或他人修改“贡献”或其他结合而将必然会侵犯到的专利权利要求。如您或您的“关联实体”直接或间接地(包括通过代理、专利被许可人或受让人),就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。 3. 无商标许可 “本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。 4. 分发限制 您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。 5. 免责声明与责任限制 “软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。 条款结束。 如何将木兰宽松许可证,第1版,应用到您的软件 如果您希望将木兰宽松许可证,第1版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步: 1, 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字; 2, 请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中; 3, 请将如下声明文本放入每个源文件的头部注释中。 Copyright (c) [2019] [name of copyright holder] [Software Name] is licensed under the Mulan PSL v1. You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details. Mulan Permissive Software License,Version 1 Mulan Permissive Software License,Version 1 (Mulan PSL v1) August 2019 http://license.coscl.org.cn/MulanPSL Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v1 (this License) with following terms and conditions: 0. Definition Software means the program and related documents which are comprised of those Contribution and licensed under this License. Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License. Legal Entity means the entity making a Contribution and all its Affiliates. Affiliates means entities that control, or are controlled by, or are under common control with a party to this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity. Contribution means the copyrightable work licensed by a particular Contributor under this License. 1. Grant of Copyright License Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not. 2. Grant of Patent License Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed, excluding of any patent claims solely be infringed by your or others’ modification or other combinations. If you or your Affiliates directly or indirectly (including through an agent, patent licensee or assignee), institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken. 3. No Trademark License No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in section 4. 4. Distribution Restriction You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software. 5. Disclaimer of Warranty and Limitation of Liability The Software and Contribution in it are provided without warranties of any kind, either express or implied. In no event shall any Contributor or copyright holder be liable to you for any damages, including, but not limited to any direct, or indirect, special or consequential damages arising from your use or inability to use the Software or the Contribution in it, no matter how it’s caused or based on which legal theory, even if advised of the possibility of such damages. End of the Terms and Conditions How to apply the Mulan Permissive Software License,Version 1 (Mulan PSL v1) to your software To apply the Mulan PSL v1 to your work, for easy identification by recipients, you are suggested to complete following three steps: i. Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner; ii. Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package; iii. Attach the statement to the appropriate annotated syntax at the beginning of each source file. Copyright (c) [2019] [name of copyright holder] [Software Name] is licensed under the Mulan PSL v1. You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.

简介

本项目是基于spring-data-jpa的orm,主要特点是像mongodb一样使用sql数据库. 展开 收起
Java
MulanPSL-1.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/cym1102/jpaHelper.git
git@gitee.com:cym1102/jpaHelper.git
cym1102
jpaHelper
jpaHelper
master

搜索帮助