1. Verbindung zu einer SQL-Datenbank (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📌 Empfehlung:
- ddl-auto=update — nur für dev,
- ddl-auto=validate — für prod (mit Migrations Flyway/Liquibase).
2. Arbeiten mit JPA/Hibernate (Wiederholung + Details)
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 (Cache und Sessions)
📄 Abhängigkeit:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>📄 Konfiguration:
spring:
redis:
host: localhost
port: 6379📄 Beispiel für die Verwendung des Caches:
@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) {}
}
}📄 Aktivierung des Caches:
@SpringBootApplication
@EnableCaching
public class DemoApplication {}4. NoSQL (Beispiel mit MongoDB)
📄 Abhängigkeit:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>📄 Konfiguration:
spring:
data:
mongodb:
uri: mongodb://localhost:27017/demo📄 Dokument:
@Document(collection = "products")
public class Product {
@Id
private String id;
private String name;
private double price;
}📄 Repository:
public interface ProductRepository extends MongoRepository<Product, String> {
List<Product> findByPriceGreaterThan(double price);
}5. Testcontainers (Integrationstests mit echter Datenbank)
📄 Abhängigkeit:
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.20.1</version>
<scope>test</scope>
</dependency>📄 Test:
@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();
}
}📌 Jetzt laufen die Tests mit einer echten PostgreSQL innerhalb von Docker.
6. H2 Database (In-Memory für Tests)
📄 Abhängigkeit:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>📄 Konfiguration:
spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username: sa
password: password📄 Zugriff auf die H2-Konsole: http://localhost:8080/h2-console
7. Flyway / Liquibase (Migrationen)
📄 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
);📌 Bei Start von Flyway werden alle Vx__*.sql ausgeführt.
8. Best Practices
- ✅ SQL-Datenbank → PostgreSQL (im Enterprise-Bereich ist dies der Standard).
- ✅ Redis → Caching von Abfragen und Speicherung von Sessions.
- ✅ Testcontainers → Für Integrationstests (besser als H2).
- ✅ Flyway → Versionskontrolle der Datenbank, ddl-auto=validate.
- ✅ DTO für API, Entities nur für die Datenbank.
- ✅ Repositories schlank (nur Zugriff auf die Datenbank), Geschäftslogik in Services.