digital-garden/_inbox/Несколько подключений к H2.md

58 lines
1.8 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
aliases:
tags:
- зрелость/🌱
date:
- - 2024-04-07
zero-link:
- "[[../garden/ru/meta/zero/00 Java разработка]]"
parents:
linked:
link: https://struchkov.dev/blog/ru/multiple-connections-to-h2/
---
Проблема с H2 в том, что когда запущено приложение, нельзя просто подключиться и посмотреть что происходит в БД.
Имеем следующее подключение к базе данных:
```yaml
spring:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:blog
password: password
username: sa
jpa:
hibernate:
ddl-auto: create-drop
database-platform: org.hibernate.dialect.H2Dialect
```
В вашем Spring приложении необходимо создать следующий `@Bean`:
```java
import org.h2.tools.Server;
@Configuration
public class BeanConfig {
@Bean(initMethod = "start", destroyMethod = "stop")
public Server inMemoryH2DatabaseaServer() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9090");
}
}
```
Это фактически создает сервер для остальных подключений к H2.
> [!WARNING]
> Если класс `org.h2.tools.Server` не находится, то скорее всего у зависимости для H2 установлен scope `runtime`. Удалите значение `scope` и класс появится.
Теперь можно подсоединиться к H2 используя следующий url:
```text
jdbc:h2:tcp://localhost:9090/mem:blog
```
Ограничение этого способа в том, что ==нельзя подключиться к базе, если приложение не работает.==