diff --git a/ydb/docs/en/core/integrations/orm/_includes/toc-table.md b/ydb/docs/en/core/integrations/orm/_includes/toc-table.md index 8fb4fa3ed3dd..f4119db4c179 100644 --- a/ydb/docs/en/core/integrations/orm/_includes/toc-table.md +++ b/ydb/docs/en/core/integrations/orm/_includes/toc-table.md @@ -1,7 +1,8 @@ # Object–relational mapping (ORM) -| Delivery System | Instruction | -| --- | --- | -| [Hibernate](https://hibernate.org/orm/) | [Instruction](../hibernate.md) | +| Delivery System | Instruction | +|-----------------------------------------------------------------|---------------------------------------| +| [Hibernate](https://hibernate.org/orm/) | [Instruction](../hibernate.md) | | [Spring Data JDBC](https://spring.io/projects/spring-data-jdbc) | [Instruction](../spring-data-jdbc.md) | +| [JOOQ](https://www.jooq.org/) | [Instruction](../jooq.md) | diff --git a/ydb/docs/en/core/integrations/orm/jooq.md b/ydb/docs/en/core/integrations/orm/jooq.md new file mode 100644 index 000000000000..e27930e227bf --- /dev/null +++ b/ydb/docs/en/core/integrations/orm/jooq.md @@ -0,0 +1,202 @@ +# JOOQ extension for {{ ydb-short-name }} + +This guide explains how to use [JOOQ](https://www.jooq.org/) with {{ ydb-short-name }}. + +JOOQ is a Java library that allows you to create type-safe SQL queries by generating Java classes from a database schema and providing convenient query builders. + +## Generating Java Classes {#generated-java-classes} + +You can generate Java classes using any of the tools provided on the [official JOOQ website](https://www.jooq.org/doc/latest/manual/code-generation/codegen-configuration/). Two dependencies are required: the [{{ ydb-short-name }} JDBC driver](https://github.com/ydb-platform/ydb-jdbc-driver) and the JOOQ extension for {{ ydb-short-name }}, along with two parameters: + +- `database.name`: `tech.ydb.jooq.codegen.YdbDatabase` (mandatory setting) +- `strategy.name`: `tech.ydb.jooq.codegen.YdbGeneratorStrategy` (recommended setting) + +An example using the `maven` plugin: + +```xml + + org.jooq + jooq-codegen-maven + 3.19.11 + + + + generate + + + + + + tech.ydb.jdbc + ydb-jdbc-driver + ${ydb.jdbc.version} + + + tech.ydb.dialects + jooq-ydb-dialect + ${jooq.ydb.version} + + + + + tech.ydb.jdbc.YdbDriver + jdbc:ydb:grpc://localhost:2136/local + + + + tech.ydb.jooq.codegen.YdbGeneratorStrategy + + + tech.ydb.jooq.codegen.YdbDatabase + + .sys.* + + + ydb + ./src/main/java + + + + +``` + +Example of generated classes from [YQL tutorial](../../dev/yql-tutorial/create_demo_tables.md) (full file contents are [available on GitHub](https://github.com/ydb-platform/ydb-java-examples/tree/master/jdbc/spring-jooq/src/main/java/ydb/default_schema)): + +```text +ydb/DefaultCatalog.java +ydb/default_schema +ydb/default_schema/tables +ydb/default_schema/tables/Seasons.java +ydb/default_schema/tables/records +ydb/default_schema/tables/records/SeriesRecord.java +ydb/default_schema/tables/records/EpisodesRecord.java +ydb/default_schema/tables/records/SeasonsRecord.java +ydb/default_schema/tables/Series.java +ydb/default_schema/tables/Episodes.java +ydb/default_schema/Indexes.java +ydb/default_schema/Keys.java +ydb/default_schema/Tables.java +ydb/default_schema/DefaultSchema.java +``` + +## Usage {#usage} + +To integrate {{ ydb-short-name }} with JOOQ into your project, you need to add two dependencies: {{ ydb-short-name }} JDBC Driver and the JOOQ extension for {{ ydb-short-name }}. + +Examples for different build systems: + +{% list tabs %} + +- Maven + + ```xml + + + tech.ydb.jdbc + ydb-jdbc-driver + ${ydb.jdbc.version} + + + + tech.ydb.dialects + jooq-ydb-dialect + ${jooq.ydb.dialect.version} + + ``` + +- Gradle + + ```groovy + dependencies { + // Set actual versions + implementation "tech.ydb.dialects:jooq-ydb-dialect:$jooqYdbDialectVersion" + implementation "tech.ydb.jdbc:ydb-jdbc-driver:$ydbJdbcVersion" + } + ``` + +{% endlist %} + +To obtain a `YdbDSLContext` class instance (an extension of `org.jooq.DSLContext`), use the `tech.ydb.jooq.YDB` class. For example: + +```java +String url = "jdbc:ydb:://:/path/to/database[?saFile=file:~/sa_key.json]"; +Connection conn = DriverManager.getConnection(url); + +YdbDSLContext dsl = YDB.using(conn); +``` + +or + +```java +String url = "jdbc:ydb:://:/path/to/database[?saFile=file:~/sa_key.json]"; +try(CloseableYdbDSLContext dsl = YDB.using(url)) { + // ... +} +``` + +`YdbDSLContext` is ready to use. + +## YQL statements + +The following statements are available from the YQL syntax in `YdbDSLContext`: + +- [`UPSERT`](../../yql/reference/syntax/upsert_into.md): + +```java +// generated SQL: +// upsert into `episodes` (`series_id`, `season_id`, `episode_id`, `title`, `air_date`) +// values (?, ?, ?, ?, ?) +public void upsert(YdbDSLContext context) { + context.upsertInto(EPISODES) + .set(record) + .execute(); +} +``` + +- [`REPLACE`](../../yql/reference/syntax/replace_into.md): + +```java +// generated SQL: +// replace into `episodes` (`series_id`, `season_id`, `episode_id`, `title`, `air_date`) +// values (?, ?, ?, ?, ?) +public void replace(YdbDSLContext context) { + ydbDSLContext.replaceInto(EPISODES) + .set(record) + .execute(); +} +``` + +- `VIEW index_name`: + +```java +// generated SQL: +// select `series`.`series_id`, `series`.`title`, `series`.`series_info`, `series`.`release_date` +// from `series` view `title_name` where `series`.`title` = ? +var record = ydbDSLContext.selectFrom(SERIES.useIndex(Indexes.TITLE_NAME.name)) + .where(SERIES.TITLE.eq(title)) + .fetchOne(); +``` + +In all other respects, the {{ ydb-short-name }} dialect follows the [JOOQ documentation](https://www.jooq.org/doc/latest/manual/). + +### Spring Boot Configuration + +Extend `JooqAutoConfiguration.DslContextConfiguration` with your own `YdbDSLContext`. For example: + +```java +@Configuration +public class YdbJooqConfiguration extends JooqAutoConfiguration.DslContextConfiguration { + + @Override + public YdbDSLContextImpl dslContext(org.jooq.Configuration configuration) { + return YdbDSLContextImpl(configuration); + } +} +``` + +```properties +spring.datasource.driver-class-name=tech.ydb.jdbc.YdbDriver +spring.datasource.url=jdbc:ydb:://:/path/to/database[?saFile=file:~/sa_key.json] +``` + +A complete example of a simple Spring Boot application can be found on [GitHub](https://github.com/ydb-platform/ydb-java-examples/tree/master/jdbc/spring-jooq). diff --git a/ydb/docs/en/core/integrations/orm/toc-orm.yaml b/ydb/docs/en/core/integrations/orm/toc-orm.yaml index 963cfe6a307e..c0ac8a9be6ce 100644 --- a/ydb/docs/en/core/integrations/orm/toc-orm.yaml +++ b/ydb/docs/en/core/integrations/orm/toc-orm.yaml @@ -2,4 +2,6 @@ items: - name: Spring Data JDBC href: spring-data-jdbc.md - name: Hibernate - href: hibernate.md \ No newline at end of file + href: hibernate.md +- name: JOOQ + href: jooq.md \ No newline at end of file diff --git a/ydb/docs/ru/core/integrations/orm/_includes/toc-table.md b/ydb/docs/ru/core/integrations/orm/_includes/toc-table.md index 43045799afbf..34cf178295c7 100644 --- a/ydb/docs/ru/core/integrations/orm/_includes/toc-table.md +++ b/ydb/docs/ru/core/integrations/orm/_includes/toc-table.md @@ -1,6 +1,7 @@ # Объектно-реляционное отображение (ORM) -| Система | Инструкция | -| --- | --- | -| [Hibernate](https://hibernate.org/orm/) | [Инструкция](../hibernate.md) | -| [Spring Data JDBC](https://spring.io/projects/spring-data-jdbc) | [Инструкция](../spring-data-jdbc.md) | \ No newline at end of file +| Система | Инструкция | +|-----------------------------------------------------------------|--------------------------------------| +| [Hibernate](https://hibernate.org/orm/) | [Инструкция](../hibernate.md) | +| [Spring Data JDBC](https://spring.io/projects/spring-data-jdbc) | [Инструкция](../spring-data-jdbc.md) | +| [JOOQ](https://www.jooq.org/) | [Инструкция](../jooq.md) | \ No newline at end of file diff --git a/ydb/docs/ru/core/integrations/orm/jooq.md b/ydb/docs/ru/core/integrations/orm/jooq.md new file mode 100644 index 000000000000..3e736befb6aa --- /dev/null +++ b/ydb/docs/ru/core/integrations/orm/jooq.md @@ -0,0 +1,202 @@ +# Расширение JOOQ для использования с {{ ydb-short-name }} + +Это руководство предназначено для использования [JOOQ](https://www.jooq.org/) с {{ ydb-short-name }}. + +JOOQ — это библиотека для Java, которая позволяет создавать типобезопасные SQL-запросы путём генерации Java-классов из схемы базы данных и использования удобных конструкторов запросов. + +## Генерация Java-классов + +Генерировать Java-классы можно с помощью любых инструментов, представленных на [официальном сайте JOOQ](https://www.jooq.org/doc/latest/manual/code-generation/codegen-configuration/), используя две зависимости: {{ ydb-short-name }} JDBC Driver и расширение JOOQ для {{ ydb-short-name }}. Также необходимо указать два параметра: + +- `database.name`: `tech.ydb.jooq.codegen.YdbDatabase` (обязательная настройка) +- `strategy.name`: `tech.ydb.jooq.codegen.YdbGeneratorStrategy` (рекомендуется к использованию) + +Рассмотрим на примере `maven` плагина: + +```xml + + org.jooq + jooq-codegen-maven + 3.19.11 + + + + generate + + + + + + tech.ydb.jdbc + ydb-jdbc-driver + ${ydb.jdbc.version} + + + tech.ydb.dialects + jooq-ydb-dialect + ${jooq.ydb.version} + + + + + tech.ydb.jdbc.YdbDriver + jdbc:ydb:grpc://localhost:2136/local + + + + tech.ydb.jooq.codegen.YdbGeneratorStrategy + + + tech.ydb.jooq.codegen.YdbDatabase + + .sys.* + + + ydb + ./src/main/java + + + + +``` + +Пример сгенерированных классов из [туториала по YQL](../../dev/yql-tutorial/create_demo_tables.md) (их полный код [доступен на GitHub](https://github.com/ydb-platform/ydb-java-examples/tree/master/jdbc/spring-jooq/src/main/java/ydb/default_schema)): + +```text +ydb/DefaultCatalog.java +ydb/default_schema +ydb/default_schema/tables +ydb/default_schema/tables/Seasons.java +ydb/default_schema/tables/records +ydb/default_schema/tables/records/SeriesRecord.java +ydb/default_schema/tables/records/EpisodesRecord.java +ydb/default_schema/tables/records/SeasonsRecord.java +ydb/default_schema/tables/Series.java +ydb/default_schema/tables/Episodes.java +ydb/default_schema/Indexes.java +ydb/default_schema/Keys.java +ydb/default_schema/Tables.java +ydb/default_schema/DefaultSchema.java +``` + +## Использование + +Для интеграции {{ ydb-short-name }} с JOOQ в ваш проект потребуется добавить две зависимости: {{ ydb-short-name }} JDBC Driver и расширение JOOQ для {{ ydb-short-name }}. + +Примеры для различных систем сборки: + +{% list tabs %} + +- Maven + + ```xml + + + tech.ydb.jdbc + ydb-jdbc-driver + ${ydb.jdbc.version} + + + + tech.ydb.dialects + jooq-ydb-dialect + ${jooq.ydb.dialect.version} + + ``` + +- Gradle + + ```groovy + dependencies { + // Set actual versions + implementation "tech.ydb.dialects:jooq-ydb-dialect:$jooqYdbDialectVersion" + implementation "tech.ydb.jdbc:ydb-jdbc-driver:$ydbJdbcVersion" + } + ``` + +{% endlist %} + +Для получения `YdbDSLContext` (расширение `org.jooq.DSLContext`) используйте класс `tech.ydb.jooq.YDB`. Например: + +```java +String url = "jdbc:ydb:://:/path/to/database[?saFile=file:~/sa_key.json]"; +Connection conn = DriverManager.getConnection(url); + +YdbDSLContext dsl = YDB.using(conn); +``` + +или + +```java +String url = "jdbc:ydb:://:/path/to/database[?saFile=file:~/sa_key.json]"; +try(CloseableYdbDSLContext dsl = YDB.using(url)) { + // ... +} +``` + +`YdbDSLContext` готов к использованию. + +## YQL команды + +В `YdbDSLContext` доступны следующие команды, специфичные для синтаксиса YQL: + +- [`UPSERT`](../../yql/reference/syntax/upsert_into.md): + +```java +// generated SQL: +// upsert into `episodes` (`series_id`, `season_id`, `episode_id`, `title`, `air_date`) +// values (?, ?, ?, ?, ?) +public void upsert(YdbDSLContext context) { + context.upsertInto(EPISODES) + .set(record) + .execute(); +} +``` + +- [`REPLACE`](../../yql/reference/syntax/replace_into.md): + +```java +// generated SQL: +// replace into `episodes` (`series_id`, `season_id`, `episode_id`, `title`, `air_date`) +// values (?, ?, ?, ?, ?) +public void replace(YdbDSLContext context) { + ydbDSLContext.replaceInto(EPISODES) + .set(record) + .execute(); +} +``` + +- `VIEW index_name`: + +```java +// generated SQL: +// select `series`.`series_id`, `series`.`title`, `series`.`series_info`, `series`.`release_date` +// from `series` view `title_name` where `series`.`title` = ? +var record = ydbDSLContext.selectFrom(SERIES.useIndex(Indexes.TITLE_NAME.name)) + .where(SERIES.TITLE.eq(title)) + .fetchOne(); +``` + +В остальном диалект {{ ydb-short-name }} соответствует [документации JOOQ](https://www.jooq.org/doc/latest/manual/). + +### Конфигурация Spring Boot + +Расширим `JooqAutoConfiguration.DslContextConfiguration` собственным `YdbDSLContext`. Например: + +```java +@Configuration +public class YdbJooqConfiguration extends JooqAutoConfiguration.DslContextConfiguration { + + @Override + public YdbDSLContextImpl dslContext(org.jooq.Configuration configuration) { + return YdbDSLContextImpl(configuration); + } +} +``` + +```properties +spring.datasource.driver-class-name=tech.ydb.jdbc.YdbDriver +spring.datasource.url=jdbc:ydb:://:/path/to/database[?saFile=file:~/sa_key.json] +``` + +Полный пример простого приложения Spring Boot можно найти [на GitHub](https://github.com/ydb-platform/ydb-java-examples/tree/master/jdbc/spring-jooq). \ No newline at end of file diff --git a/ydb/docs/ru/core/integrations/orm/toc-orm.yaml b/ydb/docs/ru/core/integrations/orm/toc-orm.yaml index 72775ad0af4d..2a82a4ac9c64 100644 --- a/ydb/docs/ru/core/integrations/orm/toc-orm.yaml +++ b/ydb/docs/ru/core/integrations/orm/toc-orm.yaml @@ -2,4 +2,6 @@ items: - name: Hibernate href: hibernate.md - name: Spring Data JDBC - href: spring-data-jdbc.md \ No newline at end of file + href: spring-data-jdbc.md +- name: JOOQ + href: jooq.md \ No newline at end of file