Skip to content

Commit 0674eeb

Browse files
feat: integration spring data jdbc docs (#8582)
Co-authored-by: Ivan Blinkov <ivan@ydb.tech>
1 parent c75b079 commit 0674eeb

File tree

4 files changed

+342
-0
lines changed

4 files changed

+342
-0
lines changed
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
# {{ ydb-short-name }} Dialect for Spring Data JDBC
2+
3+
This guide is intended for use with [Spring Data JDBC](https://spring.io/projects/spring-data-jdbc) and {{ ydb-short-name }}.
4+
5+
Spring Data JDBC is part of the [Spring Data](https://spring.io/projects/spring-data) ecosystem, providing a simplified way to interact with relational databases using SQL and Java objects. Unlike Spring JPA, which relies on JPA (Java Persistence API), Spring Data offers a direct approach to working with databases, bypassing complex ORM (Object-Relational Mapping) for simpler methods.
6+
7+
## Installing the {{ ydb-short-name }} dialect {#install-dialect}
8+
9+
To integrate {{ ydb-short-name }} with a Spring Data JDBC project, it needs two dependencies: the [{{ ydb-short-name }} JDBC driver](https://github.com/ydb-platform/ydb-jdbc-driver/) and the Spring Data JDBC extension for {{ ydb-short-name }}.
10+
11+
Examples for different build systems:
12+
13+
{% list tabs %}
14+
15+
- Maven
16+
17+
```xml
18+
<!-- Set actual versions -->
19+
<dependency>
20+
<groupId>tech.ydb.jdbc</groupId>
21+
<artifactId>ydb-jdbc-driver</artifactId>
22+
<version>${ydb.jdbc.version}</version>
23+
</dependency>
24+
25+
<dependency>
26+
<groupId>tech.ydb.dialects</groupId>
27+
<artifactId>spring-data-jdbc-ydb</artifactId>
28+
<version>${spring.data.jdbc.ydb}</version>
29+
</dependency>
30+
```
31+
32+
- Gradle
33+
34+
```groovy
35+
dependencies {
36+
// Set actual versions
37+
implementation "tech.ydb.dialects:spring-data-jdbc-ydb:$ydbDialectVersion"
38+
implementation "tech.ydb.jdbc:ydb-jdbc-driver:$ydbJdbcVersion"
39+
}
40+
```
41+
42+
{% endlist %}
43+
44+
## Usage {#using}
45+
46+
After importing all the necessary dependencies, the dialect is ready for use. Below is a simple example of a Spring Data JDBC application.
47+
48+
```properties
49+
spring.datasource.driver-class-name=tech.ydb.jdbc.YdbDriver
50+
spring.datasource.url=jdbc:ydb:<grpc/grpcs>://<host>:<2135/2136>/path/to/database[?saFile=file:~/sa_key.json]
51+
```
52+
53+
```java
54+
@Table(name = "Users")
55+
public class User implements Persistable<Long> {
56+
@Id
57+
private Long id = ThreadLocalRandom.current().nextLong();
58+
59+
private String login;
60+
private String firstname;
61+
private String lastname;
62+
63+
@Transient
64+
private boolean isNew;
65+
66+
// Constructors, getters and setters
67+
68+
@Override
69+
public Long getId() {
70+
return id;
71+
}
72+
73+
@Override
74+
public boolean isNew() {
75+
return isNew;
76+
}
77+
78+
public void setNew(boolean isNew) {
79+
this.isNew = isNew;
80+
}
81+
}
82+
```
83+
84+
Creating a repository for the `User` entity in the `Users` table:
85+
86+
```java
87+
public interface SimpleUserRepository extends CrudRepository<User, Long> {
88+
}
89+
```
90+
91+
Saving a new user and verifying that it has been successfully saved:
92+
93+
```java
94+
@Component
95+
public class UserRepositoryCommandLineRunner implements CommandLineRunner {
96+
97+
@Autowired
98+
private SimpleUserRepository repository;
99+
100+
@Override
101+
public void run(String... args) {
102+
User user = new User();
103+
user.setLogin("johndoe");
104+
user.setFirstname("John");
105+
user.setLastname("Doe");
106+
user.setNew(true); // Setting the flag for the new entity
107+
108+
// Save user
109+
User savedUser = repository.save(user);
110+
111+
// Check saved user
112+
assertThat(repository.findById(savedUser.getId())).contains(savedUser);
113+
114+
System.out.println("User saved with ID: " + savedUser.getId());
115+
}
116+
}
117+
```
118+
119+
### View Index {#viewIndex}
120+
121+
To generate `VIEW INDEX` statements from repository methods, use the `@ViewIndex` annotation. The `@ViewIndex` annotation has two fields:
122+
123+
- `indexName`: The index name.
124+
- `tableName`: The table name to which the `VIEW INDEX` is bound, which is particularly useful when using the `@MappedCollection` annotation.
125+
126+
Here is an example of an index on the Users table by the `login` field:
127+
128+
```java
129+
public interface SimpleUserRepository extends CrudRepository<User, Long> {
130+
131+
@ViewIndex(indexName = "login_index")
132+
User findByLogin(String login);
133+
}
134+
```
135+
136+
The query generated by this method will look as follows:
137+
138+
```sql
139+
SELECT
140+
`Users`.`id` AS `id`,
141+
`Users`.`login` AS `login`,
142+
`Users`.`lastname` AS `lastname`,
143+
`Users`.`firstname` AS `firstname`
144+
FROM `Users` VIEW login_index AS `Users` WHERE `Users`.`login` = ?
145+
```
146+
147+
### YdbType {#ydbType}
148+
149+
The `@YdbType` annotation allows you to declare a specific {{ ydb-short-name }} data type for an entity field. Here is an example of its usage:
150+
151+
```java
152+
@YdbType("Json")
153+
private String jsonColumn;
154+
@YdbType("JsonDocument")
155+
private String jsonDocumentColumn;
156+
@YdbType("Uint8")
157+
private byte uint8Column;
158+
@YdbType("Uint16")
159+
private short uint16Column;
160+
@YdbType("Uint32")
161+
private int uint32Column;
162+
@YdbType("Uint64")
163+
private long uint64Column;
164+
```
165+
166+
Using the `@YdbType` annotation allows you to accurately specify the data types supported by {{ ydb-short-name }}, ensuring proper interaction with the database.
167+
168+
A complete example of a simple Spring Data JDBC repository is available [on GitHub](https://github.com/ydb-platform/ydb-java-examples/tree/master/jdbc/spring-data-jdbc).

ydb/docs/en/core/integrations/toc_i.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,5 @@ items:
1919
href: ide/dbeaver.md
2020
- name: DataGrip
2121
href: ide/datagrip.md
22+
- name: Spring Data JDBC
23+
href: spring-data-jdbc.md
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
# Диалект {{ ydb-short-name }} для Spring Data JDBC
2+
3+
Это руководство предназначено для использования [Spring Data JDBC](https://spring.io/projects/spring-data-jdbc) с {{ ydb-short-name }}.
4+
5+
Spring Data JDBC является частью экосистемы [Spring Data](https://spring.io/projects/spring-data), которая предоставляет упрощенный подход к взаимодействию с реляционными базами данных посредством использования SQL и простых Java объектов. В отличие от [Spring Data JPA](https://spring.io/projects/spring-data-jpa), который построен на базе JPA (Java Persistence API), Spring Data JDBC предлагает более прямолинейный способ работы с базами данных, исключающий сложности, связанные с ORM (Object-Relational Mapping).
6+
7+
## Установка диалекта {{ ydb-short-name }} {#install-dialect}
8+
9+
Для интеграции {{ ydb-short-name }} с вашим проектом Spring Data JDBC потребуется добавить две зависимости: {{ ydb-short-name }} JDBC Driver и расширение Spring Data JDBC для {{ ydb-short-name }}.
10+
11+
Примеры для различных систем сборки:
12+
13+
{% list tabs %}
14+
15+
- Maven
16+
17+
```xml
18+
<!-- Set actual versions -->
19+
<dependency>
20+
<groupId>tech.ydb.jdbc</groupId>
21+
<artifactId>ydb-jdbc-driver</artifactId>
22+
<version>${ydb.jdbc.version}</version>
23+
</dependency>
24+
25+
<dependency>
26+
<groupId>tech.ydb.dialects</groupId>
27+
<artifactId>spring-data-jdbc-ydb</artifactId>
28+
<version>${spring.data.jdbc.ydb}</version>
29+
</dependency>
30+
```
31+
32+
- Gradle
33+
34+
```groovy
35+
dependencies {
36+
// Set actual versions
37+
implementation "tech.ydb.dialects:spring-data-jdbc-ydb:$ydbDialectVersion"
38+
implementation "tech.ydb.jdbc:ydb-jdbc-driver:$ydbJdbcVersion"
39+
}
40+
```
41+
42+
{% endlist %}
43+
44+
## Использование {#using}
45+
46+
После импорта всех необходимых зависимостей диалект готов к использованию. Рассмотрим простой пример Spring Data JDBC приложения.
47+
48+
```properties
49+
spring.datasource.driver-class-name=tech.ydb.jdbc.YdbDriver
50+
spring.datasource.url=jdbc:ydb:<grpc/grpcs>://<host>:<2135/2136>/path/to/database[?saFile=file:~/sa_key.json]
51+
```
52+
53+
```java
54+
@Table(name = "Users")
55+
public class User implements Persistable<Long> {
56+
@Id
57+
private Long id = ThreadLocalRandom.current().nextLong();
58+
59+
private String login;
60+
private String firstname;
61+
private String lastname;
62+
63+
@Transient
64+
private boolean isNew;
65+
66+
// Конструкторы, геттеры и сеттеры
67+
68+
@Override
69+
public Long getId() {
70+
return id;
71+
}
72+
73+
@Override
74+
public boolean isNew() {
75+
return isNew;
76+
}
77+
78+
public void setNew(boolean isNew) {
79+
this.isNew = isNew;
80+
}
81+
}
82+
```
83+
84+
Для сущности `User` таблицы `Users` создадим репозиторий:
85+
86+
```java
87+
public interface SimpleUserRepository extends CrudRepository<User, Long> {
88+
}
89+
```
90+
91+
Давайте сохраним нового пользователя и проверим, что он был успешно сохранен:
92+
93+
```java
94+
@Component
95+
public class UserRepositoryCommandLineRunner implements CommandLineRunner {
96+
97+
@Autowired
98+
private SimpleUserRepository repository;
99+
100+
@Override
101+
public void run(String... args) {
102+
User user = new User();
103+
user.setLogin("johndoe");
104+
user.setFirstname("John");
105+
user.setLastname("Doe");
106+
user.setNew(true); // Устанавливаем флаг новой сущности
107+
108+
// Сохранение пользователя
109+
User savedUser = repository.save(user);
110+
111+
// Проверка сохранения пользователя
112+
assertThat(repository.findById(savedUser.getId())).contains(savedUser);
113+
114+
System.out.println("User saved with ID: " + savedUser.getId());
115+
}
116+
}
117+
```
118+
119+
### View Index {#viewIndex}
120+
121+
Для генерации конструкций `VIEW INDEX` из методов репозитория необходимо использовать аннотацию `@ViewIndex`.
122+
Аннотация `@ViewIndex` имеет два поля:
123+
124+
- `indexName` - название индекса.
125+
- `tableName` - название таблицы, к которой привязан `VIEW INDEX`, особенно полезно при использовании аннотаций `@MappedCollection`.
126+
127+
Рассмотрим простой пример с индексом таблицы Users по полю `login`:
128+
129+
```java
130+
public interface SimpleUserRepository extends CrudRepository<User, Long> {
131+
132+
@ViewIndex(indexName = "login_index")
133+
User findByLogin(String login);
134+
}
135+
```
136+
137+
Запрос, который сгенерирует этот метод, будет выглядеть следующим образом:
138+
139+
```sql
140+
SELECT `Users`.`id` AS `id`,
141+
`Users`.`login` AS `login`,
142+
`Users`.`lastname` AS `lastname`,
143+
`Users`.`firstname` AS `firstname`
144+
FROM `Users` VIEW login_index AS `Users`
145+
WHERE `Users`.`login` = ?
146+
```
147+
148+
### YdbType {#ydbType}
149+
150+
Для указания конкретного типа данных в {{ ydb-short-name }} можно использовать аннотацию `@YdbType` над полем сущности.
151+
Пример использования:
152+
153+
```java
154+
@YdbType("Json")
155+
private String jsonColumn;
156+
@YdbType("JsonDocument")
157+
private String jsonDocumentColumn;
158+
@YdbType("Uint8")
159+
private byte uint8Column;
160+
@YdbType("Uint16")
161+
private short uint16Column;
162+
@YdbType("Uint32")
163+
private int uint32Column;
164+
@YdbType("Uint64")
165+
private long uint64Column;
166+
```
167+
168+
Использование аннотации `@YdbType` позволяет точно указать типы данных, поддерживаемые {{ ydb-short-name }}, что обеспечивает корректное взаимодействие с базой данных.
169+
170+
Пример простого приложения Spring Data JDBC можно найти по [ссылке](https://github.com/ydb-platform/ydb-java-examples/tree/master/jdbc/spring-data-jdbc).

ydb/docs/ru/core/integrations/toc_i.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,5 @@ items:
1919
href: ide/dbeaver.md
2020
- name: DataGrip
2121
href: ide/datagrip.md
22+
- name: Spring Data JDBC
23+
href: spring-data-jdbc.md

0 commit comments

Comments
 (0)