diff --git a/README.md b/README.md index 3a70815c386e9d2803d90d41de4cc9139d6926fd..d64fbbab520fadd756546dafef604e49e2491c83 100644 --- a/README.md +++ b/README.md @@ -1,161 +1,326 @@ -# database +# Gaarason Database -[![](https://jitpack.io/v/gaarason/database-all.svg)](https://jitpack.io/#gaarason/database-all) -[![](https://img.shields.io/github/stars/gaarason/database-all)](https://github.com/gaarason/database-all) +Gaarason Database 是一个基于 Java 的 ORM 框架,旨在提供简洁、高效的数据库操作方式。它支持多种数据库类型,并提供了诸如实体关系映射、查询构造器、事务管理、分页、序列化等功能。 -[![](https://img.shields.io/badge/JDK-8-green.svg)]() -[![](https://img.shields.io/badge/JDK-11-green.svg)]() -[![](https://img.shields.io/badge/JDK-17-green.svg)]() -[![](https://img.shields.io/badge/JDK-21-green.svg)]() -[![](https://img.shields.io/badge/JDK-23-green.svg)]() +## 简介 -[![](https://img.shields.io/badge/SpringBoot-v2.x-blue.svg)]() -[![](https://img.shields.io/badge/SpringBoot-v3.x-blue.svg)]() +Gaarason Database 提供了类似于 Laravel Eloquent 的风格,使开发者能够以面向对象的方式进行数据库操作。它支持 Spring Boot 集成,并且可以与 Druid、Hikari 等连接池配合使用。 +## 目录 -Eloquent ORM for Java +- [快速开始](#快速开始) +- [配置](#配置) +- [模型与实体](#模型与实体) +- [查询构造器](#查询构造器) +- [关系映射](#关系映射) +- [事务管理](#事务管理) +- [分页](#分页) +- [序列化与深拷贝](#序列化与深拷贝) +- [生成器](#生成器) +- [日志与调试](#日志与调试) +- [测试与验证](#测试与验证) -## 简介 Introduction +## 快速开始 -- 让连接数据库以及对数据库进行增删改查操作变得非常简单,不论希望使用原生 SQL、还是查询构造器,还是 Eloquent ORM。 -- Eloquent ORM 提供一个美观、简单的与数据库打交道的 ActiveRecord - 实现,每个数据表都对应一个与该表数据结构对应的实体(Entity),以及的进行交互的模型(Model),通过模型类,你可以对数据表进行查询、插入、更新、删除等操作,并将结果反映到实体实例化的 java 对象中。 -- 对于关联关系 Eloquent ORM 提供了富有表现力的声明方式,与简洁的使用方法,并专注在内部进行查询与内存优化,在复杂的关系中有仍然有着良好的体验。 -- 支持完全自定义的查询构造器与SQL语法, 类型转化以及关联关系。 -- 支持原生Java8,Java11,Java17,Java21,Java23 应用, 支持SpringBoot 2x 以及 3x ,兼容于其他常见的 ORM 框架, 以及常见的数据源 (DataSource), 以及所有 JDBC 支持的数据库。 -*** -- It makes connecting to the database and adding, deleting, modifying and querying the database very simple, whether you want to use native SQL, query builder, or Eloquent ORM. -- Eloquent ORM provides a beautiful and simple ActiveRecord for working with databases - Implementation, each data table corresponds to an entity (Entity) corresponding to the data structure of the table, and a model (Model) for interaction. Through the model class, you can query, insert, update, delete and other operations on the data table , and reflect the results into the java object instantiated by the entity. -- For relationships, Eloquent ORM provides expressive declaration methods and concise usage methods. It focuses on internal query and memory optimization, and still has a good experience in complex relationships. -- Support fully customizable query constructors, SQL syntax, type conversion, and association relationships -- Supports native Java8, Java11, Java17 , Java21 applications, supports SpringBoot 2x and 3x, and is compatible with other common ORM frameworks and common data sources (DataSource), and all databases supported by JDBC. +### 使用你喜欢的数据源 -## 目录 +Gaarason Database 支持多种数据源,包括 Druid 和 HikariCP。你可以通过以下方式配置数据源: + +```java +GaarasonDataSource dataSource = GaarasonDataSourceBuilder.build(dataSource); +``` + +如果你希望使用读写分离或多个数据源,也可以传入主从数据源列表: + +```java +GaarasonDataSource dataSource = GaarasonDataSourceBuilder.build(masterList, slaveList); +``` + +### 雪花算法工作 ID + +如果你使用雪花算法生成主键 ID,可以通过以下方式设置工作节点 ID: + +```properties +gaarason.database.snow-flake.worker-id=1 +``` + +### 包扫描路径 -* [注册配置 Configuration](/document/bean.md) -* [数据映射 Mapping](/document/mapping.md) -* [数据模型 Model](/document/model.md) -* [查询结果集 Record](/document/record.md) -* [查询构造器 Query Builder](/document/query.md) -* [关联关系 Relationship](/document/relationship.md) -* [生成代码 Generate](/document/generate.md) -* [GraalVM](/document/graalvm.md) -* [版本信息 Version](/document/version.md) +默认情况下,Gaarason 会扫描 `@SpringBootApplication` 注解所在的包。如果你没有使用 Spring Boot,建议手动指定扫描路径: -- 以如下的方式在程序中查询数据 Query data in the program in the following way -- 查询 Select : model.newQuery().select().where().get(); -- 更新 Update : model.newQuery().data().where().update(); -- 删除 Delete : model.newQuery().where().delete(); -- 插入 Insert : model.newQuery().column().value().insert(); +```properties +gaarason.database.scan.packages=com.example.model +``` + +## 完整体验 + +你可以通过 Spring Boot 快速集成 Gaarason Database 并体验其完整的功能,包括 ORM、事务、关系映射等。 + +### 示例模型 ```java -// select * from student where id = 4 limit 1 -Student student = studentModel.find(4).toObject(); +@Table(name = "student") +public class Student implements Serializable { + @Primary + private Integer id; -// select * from student where id = 4 limit 1 -Student student = studentModel.newQuery().query("select * from student where id= ? limit ? ", 4, 1).toObject(); + @Column(name = "name") + private String name; -// select name,age from student where id in (1, 2, 3) -List students = studentModel.newQuery() - .select(Student::getName).select(Student::getAge) - .whereIn(Student::getId, 1, 2, 3) - .get().toObjectList(); + @Column(name = "age") + private Integer age; +} -// select id,name from student where id=3 or(age>11 and id=7 and(id between 4 and 10 and age>11)) -List students = studentModel.newQuery().where("id", "3").orWhere( - builder->builder.where("age", ">", "11").where("id", "7").andWhere( - builder2->builder2.whereBetween("id", "4", "10").where("age", ">", "11") - ) -).select("id", "name").get().toObjectList(); +@Repository +public class StudentModel extends Model, Student, Integer> { + @Override + public GaarasonDataSource getGaarasonDataSource() { + return dataSource; + } +} +``` -// select * from student where id in (1, 2, 3) -// select * from teacher where id in (?, ?, ?) -// select * from father where id in (?, ?, ?) -// select * from house where owner_id in (?, ?, ?) -List students = studentModel.newQuery().whereIn("id", 1, 2, 3).get().with("teacher.father.house").toObjectList(); +### 查询操作 -// select * from student where id = 8 limit 1 -// select * from relation_student_teacher where student_id = 8 and teacher_id in (1, 2, 3) -// insert into relation_student_teacher set student_id = 8 and teacher_id = 3 -studentModel.findOrFail(8).bind("teachers").attach( 1, 2, 3 ); +```java +StudentModel studentModel = new StudentModel(); +Record record = studentModel.newQuery().where("age", ">", 18).first(); +System.out.println(record.getEntity()); ``` -## Spring boot Quick start +### 插入操作 -1.引入仓库 pom.xml +```java +Student student = new Student(); +student.setName("Alice"); +student.setAge(20); -```xml - - - jitpack.io - https://jitpack.io - - +Record record = studentModel.newRecord(student); +record.save(); ``` -2.引入依赖 pom.xml +### 更新操作 -**latest-version**:![](https://jitpack.io/v/gaarason/database-all.svg) +```java +Record record = studentModel.find(1); +record.getEntity().setAge(25); +record.save(); +``` -```xml - - com.github.gaarason.database-all - database-spring-boot-starter - {latest-version} - +### 删除操作 + +```java +Record record = studentModel.find(1); +record.delete(); // 软删除 +record.forceDelete(); // 硬删除 ``` -3.配置连接 application.properties +## 配置 -```properties -spring.datasource.url=jdbc:mysql://mysql.local/test_master_0?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=true&autoReconnect=true&serverTimezone=Asia/Shanghai -spring.datasource.username=root -spring.datasource.password=root -spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +### 数据库连接配置 -# 使用你喜欢的 datasource, 这边增加了 DruidDataSource 的支持, 使其符合 Spring 的指定风格 +在 `application.properties` 或 `application.yml` 中配置数据源: + +```properties spring.datasource.type=com.alibaba.druid.pool.DruidDataSource +spring.datasource.druid.url=jdbc:mysql://localhost:3306/test +spring.datasource.druid.username=root +spring.datasource.druid.password=123456 +``` + +### ORM 配置 + +```properties +gaarason.database.scan.packages=com.example.model +gaarason.database.snow-flake.worker-id=1 +gaarason.database.snow-flake.data-id=1 +``` + +## 模型与实体 + +### 注解说明 + +- `@Table`: 标记实体类对应的数据库表。 +- `@Primary`: 标记主键字段,支持自增和雪花算法。 +- `@Column`: 标记普通字段,支持字段填充、类型转换等策略。 + +### 示例模型类 + +```java +@Table(name = "student") +public class Student implements Serializable { + @Primary(idGenerator = IdGenerator.SnowFlakesID.class) + private Long id; + + @Column(name = "name", length = 50) + private String name; + + @Column(name = "age") + private Integer age; -# 雪花算法工作id, 默认是0 -# gaarason.database.snow-flake.worker-id=1 + // Getter and Setter +} +``` + +## 查询构造器 + +Gaarason 提供了链式查询构造器,支持多种查询方式,包括条件查询、排序、分组、聚合函数等。 -# 包扫描路径, 默认是`@SpringBootApplication`所在的包 -# 非 SpringBoot, 建议手动指定包扫描路径 -# gaarason.database.scan.packages=you.package1,you.package2 +### 查询示例 + +```java +RecordList students = studentModel.newQuery() + .where("age", ">", 18) + .orderBy("name", OrderBy.ASC) + .get(); ``` -4.快速开始 quick start +### 聚合函数 -使用预置的 `GeneralModel` ,无需其他定义,即可进行查询。 -Using the pre-built `GeneralModel`, no additional definitions are required to query. +```java +Integer count = studentModel.newQuery().count("age"); +Integer maxAge = studentModel.newQuery().max("age"); +``` + +### 分页查询 ```java -@Resource -GeneralModel generalModel; +Paginate paginate = studentModel.newQuery().paginate(1, 20); +``` -@Test -public void simpleQuery() { +## 关系映射 - // select * from student where id = 3 limit 1 - Record record = generalModel.newQuery().from("student").where("id", 3).firstOrFail(); +Gaarason 支持多种关系映射,包括一对一、一对多、多对多以及多态关系。 - // to map - Map stringObjectMap = record.toMap(); +### 一对一 - System.out.println(stringObjectMap); +```java +@BelongsTo(localModelForeignKey = "teacher_id") +private Teacher teacher; +``` + +### 一对多 + +```java +@HasOneOrMany(sonModelForeignKey = "student_id") +private List comments; +``` + +### 多对多 + +```java +@BelongsToMany(relationModel = Teacher.class, foreignKeyForLocalModel = "student_id", foreignKeyForTargetModel = "teacher_id") +private List teachers; +``` + +## 事务管理 + +Gaarason 支持事务操作,包括手动事务和闭包事务。 + +### 手动事务 + +```java +dataSource.begin(); +try { + studentRecord.save(); + teacherRecord.save(); + dataSource.commit(); +} catch (Exception e) { + dataSource.rollBack(); } +``` + +### 闭包事务 + +```java +dataSource.transaction(() -> { + studentRecord.save(); + teacherRecord.save(); +}); +``` + +## 分页 + +### 偏移分页 + +```java +Paginate paginate = studentModel.newQuery().paginate(1, 20); +``` + +### 游标分页 + +```java +CursorPaginate cursorPaginate = studentModel.newQuery().cursorPaginate(100, 20); +``` + +## 序列化与深拷贝 + +Gaarason 支持将 `Record` 和 `RecordList` 序列化为 JSON 字符串,也支持深拷贝。 + +### 序列化 + +```java +String json = studentRecord.serializeToString(); +``` +### 反序列化 + +```java +Record studentRecord = Record.deserialize(json); +``` + +### 深拷贝 + +```java +Record copy = studentRecord.deepCopy(); +``` + +## 生成器 + +Gaarason 提供了代码生成器,可以根据数据库表结构自动生成实体类和模型类。 + +### 使用方式 + +```java +Generator generator = new Generator("jdbc:mysql://localhost:3306/test", "root", "123456"); +generator.setEntityDir("src/main/java/com/example/entity"); +generator.setModelDir("src/main/java/com/example/model"); +generator.run(); +``` + +## 日志与调试 + +Gaarason 支持多种日志实现,包括 SLF4J、Log4j、JDK Logging 筜。 + +### 启用日志 + +```java +LogFactory.useSLF4JLogging(); +Log logger = LogFactory.getLog(StudentModel.class); +``` + +### SQL 日志输出 + +```java +studentModel.newQuery().where("age", ">", 18).log(); +``` + +## 测试与验证 + +Gaarason 提供了丰富的单元测试和集成测试,涵盖 ORM、事务、关系映射、分页、异步查询等功能。 + +### 示例测试类 + +```java +public class StudentORMTests extends BaseTests { + @Test + public void testORM() { + Record record = studentModel.newQuery().first(); + assertNotNull(record); + } +} ``` -## 完整体验 Complete experience +## 总结 -- 借助 [生成代码 Generate](/document/generate.md), 自动化地为每个数据表都定义一个与该表数据结构对应的实体(Entity), 以及的进行交互的模型(Model) -- 在模型(Model)中, 通过 [查询构造器 Query Builder](/document/query.md) 你可以对数据表进行查询、插入、更新、删除等操作,并将结果反映到 [查询结果集 Record](/document/record.md) 中 -- 在 [查询结果集 Record](/document/record.md) 中可以快速的将结果转化为的 java 实体(Entity)对象, 以及其他数据结构以及处理操作 -- 通过在实体(Entity)中应用各种的声明式注解进行 [数据映射 Mapping](/document/mapping.md), 便可以方便的在模型(Model)中应用诸如 [关联关系 Relationship](/document/relationship.md)、ORM以及各种自定义操作 -*** -- With the help of [生成代码 Generate](/document/generate.md), each data table is automatically defined with an entity (Entity) corresponding to the data structure of the table, and a model (Model) for interaction. -- In the model, through the [查询构造器 Query Builder](/document/query.md) you can query, insert, update, delete and other operations on the data table, and reflect the results to the [查询结果集 Record](/document/record.md) in -- In [查询结果集 Record](/document/record.md), the results can be quickly converted into java entity objects, as well as other data structures and processing operations. -- By applying various declarative annotations to [数据映射 Mapping](/document/mapping.md) in the Entity, you can easily apply [关联关系 Relationship](/document/relationship.md), ORM and various custom operations +Gaarason Database 是一个功能强大、易于使用的 Java ORM 框架,支持多种数据库、连接池、事务、关系映射、分页、序列化等特性。无论是小型项目还是大型企业级应用,Gaarason 都能提供良好的支持。 \ No newline at end of file