1. Подключение SQL-базы (PostgreSQL / MySQL)
📄 pom.xml:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>📄 application.yml:
spring:
datasource:
url: jdbc:postgresql://localhost:5432/demo
username: demo
password: secret
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: validate # create, update, validate, none
show-sql: true
properties:
hibernate.format_sql: true📌 Рекомендация:
- ddl-auto=update — только на dev,
- ddl-auto=validate — на prod (с миграциями Flyway/Liquibase).
2. Работа с JPA/Hibernate (повторение + детали)
Entity:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable=false)
private String name;
private String email;
}Repository:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByEmailContaining(String part);
}3. Redis (кеш и сессии)
📄 Зависимость:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>📄 Настройка:
spring:
redis:
host: localhost
port: 6379📄 Пример использования кеша:
@Service
public class UserService {
@Cacheable("users")
public User findById(Long id) {
simulateSlowService();
return repo.findById(id).orElseThrow();
}
@CacheEvict(value = "users", key = "#id")
public void delete(Long id) {
repo.deleteById(id);
}
private void simulateSlowService() {
try { Thread.sleep(3000); } catch (InterruptedException ignored) {}
}
}📄 Включаем кеш:
@SpringBootApplication
@EnableCaching
public class DemoApplication {}4. NoSQL (пример с MongoDB)
📄 Зависимость:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>📄 Настройка:
spring:
data:
mongodb:
uri: mongodb://localhost:27017/demo📄 Документ:
@Document(collection = "products")
public class Product {
@Id
private String id;
private String name;
private double price;
}📄 Репозиторий:
public interface ProductRepository extends MongoRepository<Product, String> {
List<Product> findByPriceGreaterThan(double price);
}5. Testcontainers (интеграционные тесты с реальной БД)
📄 Зависимость:
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.20.1</version>
<scope>test</scope>
</dependency>📄 Тест:
@SpringBootTest
@Testcontainers
class UserRepositoryTest {
@Container
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:15")
.withDatabaseName("demo")
.withUsername("demo")
.withPassword("secret");
@DynamicPropertySource
static void properties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
UserRepository repo;
@Test
void testSave() {
User u = new User();
u.setName("Vitaliy");
repo.save(u);
assertThat(repo.findByName("Vitaliy")).isNotEmpty();
}
}📌 Теперь тесты работают с настоящей PostgreSQL внутри Docker.
6. H2 Database (In-Memory для тестов)
📄 Зависимость:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>📄 Настройка:
spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password: password📄 Доступ к консоли H2: http://localhost:8080/h2-console
7. Flyway / Liquibase (миграции)
📄 Flyway:
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>📄 src/main/resources/db/migration/V1__init.sql:
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL
);📌 При старте Flyway применит все Vx__*.sql.
8. Best Practices
- ✅ SQL-БД → PostgreSQL (в enterprise — стандарт).
- ✅ Redis → кеширование запросов и хранение сессий.
- ✅ Testcontainers → для интеграционных тестов (лучше, чем H2).
- ✅ Flyway → контроль версий БД, ddl-auto=validate.
- ✅ DTO для API, Entities только для БД.
- ✅ Репозитории тонкие (только доступ к БД), бизнес-логика в сервисах.