db-problems-demo example added

This commit is contained in:
Александр Оруджев
2020-10-10 20:29:56 +04:00
parent b365e500e9
commit 025f56961e
8 changed files with 248 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
+79
View File
@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ru.otus</groupId>
<artifactId>db-problems-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>db-problems-demo</name>
<description>Demo project for Db usage problems </description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
+1
View File
@@ -0,0 +1 @@
Проект с миграцией для демонстрации того, как выглядит джойн нескольких таблиц при связи "многие-ко-многим"
@@ -0,0 +1,60 @@
package db.migration;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unchecked")
public class R__0002_Add_books extends BaseJavaMigration {
public static final int BOOKS_COUNT = 100_000;
@Override
public void migrate(Context context) throws Exception {
DataSource ds = new SingleConnectionDataSource(context.getConnection(), true);
NamedParameterJdbcOperations jdbc = new NamedParameterJdbcTemplate(ds);
insertBooks(jdbc);
insertBooksRelations(jdbc);
}
private void insertBooks(NamedParameterJdbcOperations jdbc) {
List<Map<String, Object>> params = new ArrayList<>(BOOKS_COUNT);
for (int i = 0; i < BOOKS_COUNT; i++) {
String bookTitle = String.format("Заголовок книги #%d", i);
String bookTextPart = String.format("Это текст книги #%d", i);
String bookText = bookTextPart.repeat( 8000 / bookTextPart.length());
params.add(new MapSqlParameterSource("title", bookTitle)
.addValue("bookText", bookText)
.getValues()
);
}
jdbc.batchUpdate("insert into books (title, book_text) values (:title, :bookText)",
params.toArray(new Map[0]));
}
private void insertBooksRelations(NamedParameterJdbcOperations jdbc) {
List<Map<String, Object>> paramsForAuthors = new ArrayList<>(BOOKS_COUNT);
List<Map<String, Object>> paramsForGenres = new ArrayList<>(BOOKS_COUNT);
for (int i = 1; i <= BOOKS_COUNT; i++) {
for (int j = 1; j <= 3; j++) {
paramsForAuthors.add(new MapSqlParameterSource("bookId", i).addValue("authorId", j).getValues());
paramsForGenres.add(new MapSqlParameterSource("bookId", i).addValue("genreId", j).getValues());
}
}
jdbc.batchUpdate("insert into books_authors (book_id, author_id) values (:bookId, :authorId)",
paramsForAuthors.toArray(new Map[0]));
jdbc.batchUpdate("insert into books_genres (book_id, genre_id) values (:bookId, :genreId)",
paramsForGenres.toArray(new Map[0]));
}
}
@@ -0,0 +1,24 @@
package ru.otus.dbproblemsdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.sql.SQLException;
/*
SELECT * FROM AUTHORS;
SELECT * FROM GENRES;
SELECT * FROM BOOKS_AUTHORS ;
SELECT * FROM BOOKS_GENRES;
SELECT * FROM BOOKS;
SELECT * FROM BOOKS_ALL_INFO ;
*/
@SpringBootApplication
public class DbProblemsDemoApplication {
public static void main(String[] args) throws SQLException {
SpringApplication.run(DbProblemsDemoApplication.class, args);
}
}
@@ -0,0 +1,13 @@
spring:
datasource:
#url: jdbc:h2:mem:testdb
url: jdbc:postgresql://localhost:5432/problems
username: postgres
password: postgres
driver-class-name: org.postgresql.Driver
initialization-mode: never
h2:
console:
enabled: true
flyway:
enabled: true
@@ -0,0 +1,23 @@
--date: 2002-10-10
--author: stvort
create table authors (id bigserial, name varchar(50), primary key (id));
create table genres (id bigserial, name varchar(50), primary key (id));
create table books (id bigserial, title varchar(50), book_text varchar(8000), primary key (id));
create table books_authors (book_id bigint not null references books (id) on delete cascade , author_id bigint not null references authors (id) on delete cascade);
create table books_genres (book_id bigint not null references books (id) on delete cascade , genre_id bigint not null references genres (id) on delete cascade);
create view books_all_info as
select b.id as "ID книги",
b.title as "Заголовок книги",
b.book_text as "Текст книги",
a.id as "ID автора",
a.name as "Имя автора",
g.id as "ID жанра",
g.name as "Название жанра"
from books b left join
books_authors ba on b.id = ba.book_id left join
books_genres bg on b.id = bg.book_id left join
authors a on ba.author_id = a.id left join
genres g on bg.genre_id = g.id;
@@ -0,0 +1,15 @@
insert into authors(id, name)
values (1, 'Админ Супервайзерович Рут'),
(2, 'Валентина Игоревна Априори'),
(3, 'Питуний Дельфинович Автостопов'),
(4, 'Инокентий Купертинович Жужа');
insert into genres(id, name)
values (1, 'Детектив'),
(2, 'Фантастика'),
(3, 'Фэнтези'),
(4, 'Техническая литература');