This guide shows how to create multi-tenant applications in Spring Boot using H2 database for simple testing and development.
1. Add Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
2. Configure H2 Database
spring.datasource.url=jdbc:h2:mem:tenantdb
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create
spring.h2.console.enabled=true
3. Tenant Aware Entity
@Entity
public class Customer {
@Id @GeneratedValue
private Long id;
private String name;
private String tenantId;
}
4. Repository with Tenant Filter
public interface CustomerRepository extends JpaRepository<Customer, Long> {
List<Customer> findByTenantId(String tenantId);
}
5. Service Layer
@Service
public class CustomerService {
private final CustomerRepository repo;
public CustomerService(CustomerRepository repo) {
this.repo = repo;
}
public Customer save(String tenantId, String name) {
return repo.save(new Customer(null, name, tenantId));
}
public List<Customer> findAll(String tenantId) {
return repo.findByTenantId(tenantId);
}
}
6. REST Controller
@RestController
@RequestMapping("/customers")
public class CustomerController {
private final CustomerService service;
public CustomerController(CustomerService service) {
this.service = service;
}
@PostMapping("/{tenantId}")
public Customer add(@PathVariable String tenantId, @RequestBody String name) {
return service.save(tenantId, name);
}
@GetMapping("/{tenantId}")
public List<Customer> get(@PathVariable String tenantId) {
return service.findAll(tenantId);
}
}
image quote pre code