Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 119 ยท Spring Boot

Spring Data REST, Spring Data LDAP and Routing DataSources

Export repositories as a REST API with Spring Data REST, read LDAP directories through Spring Data LDAP, and route each tenant to its own database with AbstractRoutingDataSource, with runnable models.

Spring Data JPA turns a repository interface into working data access code. The same repository idea reaches further than one database. In this lesson you will meet three extensions that solve very different problems with the same style: Spring Data REST, which exposes your repositories as a hypermedia REST API with almost no code, Spring Data LDAP, which maps entries in a directory server (the kind that stores company logins and address books) to Java objects, and AbstractRoutingDataSource, a small Spring class that sends each request to a different database, which is the foundation of multi-tenant applications.

Spring, a web server and an LDAP server can't run on this page, so the real code is shown read-only and two runnable plain-Java programs show the mechanisms: a routing data source with one H2 database per tenant, and a miniature "repository exporter" that turns a repository interface into HTTP endpoints with Jackson. You should know Spring Data JPA, REST controllers and Spring Boot configuration.

Spring Data REST

Spring Data REST looks at your Spring Data repositories and publishes them as REST resources. For a repository of Product entities you get GET, POST, PUT, PATCH and DELETE endpoints, paging, sorting, links between resources and a profile description, without writing a controller. Add the starter and a repository:

XML
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
Java
@Entity
public class Product {
    @Id @GeneratedValue private Long id;
    private String name;
    private BigDecimal price;
    // getters and setters
}

@RepositoryRestResource(path = "products", collectionResourceRel = "products")
public interface ProductRepository extends JpaRepository<Product, Long> {

    @RestResource(path = "cheaper-than")
    List<Product> findByPriceLessThan(@Param("max") BigDecimal max);
}

That is the whole feature. With spring.data.rest.base-path=/api set, the application serves:

Request Meaning
GET /api Index with links to every exported repository
GET /api/products?page=0&size=20&sort=name,asc A page of products
GET /api/products/7 One product, with _links
POST /api/products Create one (JSON body)
PUT /api/products/7, PATCH /api/products/7 Replace or partially update
DELETE /api/products/7 Delete
GET /api/products/search Lists exported query methods
GET /api/products/search/cheaper-than?max=20 Runs findByPriceLessThan
GET /api/profile/products ALPS metadata describing the resource

Responses use the HAL format: the data plus _links (hypermedia) and, for collections, page information:

JSON
{
  "_embedded": { "products": [ { "name": "Keyboard", "price": 49.90,
      "_links": { "self": { "href": "http://localhost:8080/api/products/1" } } } ] },
  "_links": { "self": { "href": "http://localhost:8080/api/products?page=0&size=20" } },
  "page": { "size": 20, "totalElements": 1, "totalPages": 1, "number": 0 }
}

Controlling what is exposed

Exporting every repository automatically is convenient and dangerous. Treat Spring Data REST as a tool for internal tools, admin back-ends and prototypes, and apply these rules whenever you use it:

  • Hide what should not be public. @RepositoryRestResource(exported = false) on a repository, @RestResource(exported = false) on a method, and @JsonIgnore on a field (such as a password hash).
  • Block unwanted verbs. Declare @Override @RestResource(exported = false) void delete(Product p); to remove DELETE.
  • Use projections (@Projection) to return a slimmer view, and excerpt projections to shape the list view.
  • Add validation and events. A @RepositoryEventHandler receives @HandleBeforeCreate, @HandleBeforeSave and similar events, and Bean Validation runs on writes.
  • Secure it. Protect the base path with Spring Security, and use @PreAuthorize on repository methods.
  • Think about the contract. Your database model becomes your public API: renaming a column changes a JSON field. If you need a stable, designed API, write controllers as in Building a REST API.

A miniature exporter you can run

The program below imitates the core trick of Spring Data REST: it receives a repository interface, creates an implementation at runtime with a dynamic proxy (the same mechanism Spring Data uses), and exposes it over HTTP with Jackson. It supports the collection URL with paging, the item URL, and a custom search, and it hides a method on purpose. A client then calls it.

Java Exporting a repository as a REST resource with a dynamic proxy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The JSON for the products page shows the HAL structure: embedded data, links and page numbers. The DELETE is refused because that verb was not exported, which is the same effect as @RestResource(exported = false).

Spring Data LDAP

LDAP (Lightweight Directory Access Protocol) is how many organizations store users, groups and devices in a tree called a directory. Each entry has a distinguished name (DN) such as uid=ada,ou=people,dc=example,dc=com, an objectClass list that says what kind of entry it is, and attributes such as cn (common name), sn (surname) and mail. Spring Data LDAP maps entries to Java objects and gives you repositories, like JPA does for tables. You met LDAP as a naming service in JNDI and JMX and as an authentication source in Web Security Basics.

XML
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
PROPERTIES
spring.ldap.urls=ldaps://ldap.example.com:636
spring.ldap.base=dc=example,dc=com
spring.ldap.username=cn=service,dc=example,dc=com
spring.ldap.password=${LDAP_PASSWORD}
Java
@Entry(base = "ou=people", objectClasses = { "top", "person", "organizationalPerson", "inetOrgPerson" })
public final class Person {

    @Id
    private Name dn;                                     // javax.naming.ldap.LdapName, the entry's address

    @Attribute(name = "uid")
    private String username;

    @Attribute(name = "cn")
    private String fullName;

    @Attribute(name = "sn")
    private String surname;

    @Attribute(name = "mail")
    private String email;

    @Transient
    private String comment;                              // not stored in the directory

    // getters and setters
}

public interface PersonRepository extends LdapRepository<Person> {
    Optional<Person> findByUsername(String username);
    List<Person> findBySurnameStartingWith(String prefix);
    List<Person> findByFullNameContaining(String text);
}

Derived query methods work like in JPA, but they are turned into LDAP search filters such as (&(objectclass=inetOrgPerson)(sn=Smith*)). For anything more complex, inject LdapTemplate and use its query builder:

Java
List<String> names = ldapTemplate.search(
    LdapQueryBuilder.query().base("ou=people").where("objectclass").is("person").and("mail").like("*@example.com"),
    (AttributesMapper<String>) attrs -> (String) attrs.get("cn").get());

Practical points: use LDAPS or StartTLS in production; never log bind passwords; LDAP is optimized for reads and searches, not for transactions or complex joins, so keep write operations rare. For tests, Spring Boot can start an embedded UnboundID server from an LDIF file (spring.ldap.embedded.ldif=classpath:test-users.ldif, spring.ldap.embedded.base-dn=dc=example,dc=com), which gives repeatable tests without an external server. To log users in against LDAP (rather than store data), use Spring Security's LDAP authentication, covered in Spring Security.

Routing DataSources: one app, many databases

In a multi-tenant application, each customer (tenant) may have a separate database, or the primary and read replica may need different traffic. AbstractRoutingDataSource is a Spring class that looks like one DataSource but chooses the real one per call. You supply a map of target data sources and implement one method that returns the current lookup key:

Java
public class TenantRoutingDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return TenantContext.get();                       // e.g. "acme", or null for the default
    }
}

public final class TenantContext {
    private static final ThreadLocal<String> CURRENT = new ThreadLocal<>();
    public static void set(String tenant) { CURRENT.set(tenant); }
    public static String get() { return CURRENT.get(); }
    public static void clear() { CURRENT.remove(); }
}

@Configuration
public class DataSourceConfig {
    @Bean
    public DataSource dataSource() {
        TenantRoutingDataSource routing = new TenantRoutingDataSource();
        routing.setTargetDataSources(Map.of(
            "acme",   hikari("jdbc:postgresql://db1/acme"),
            "globex", hikari("jdbc:postgresql://db1/globex")));
        routing.setDefaultTargetDataSource(hikari("jdbc:postgresql://db1/shared"));
        return routing;                                   // afterPropertiesSet() runs as a bean
    }
}

@Component
public class TenantFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        try {
            TenantContext.set(req.getHeader("X-Tenant-Id"));      // or from the host name or the JWT
            chain.doFilter(req, res);
        } finally {
            TenantContext.clear();                                // never leak a tenant to the next request
        }
    }
}

Two rules decide whether this works. First, the key must be set before the connection is obtained: with @Transactional, Spring fetches the connection when the transaction begins, so the tenant must be chosen by a filter or interceptor before the transactional method is entered. Second, always clear the thread-local in a finally block, because servers reuse threads and the next request would otherwise run against the previous tenant's database, a serious data leak.

The same class routes read/write splitting: the key is "readOnly" when the current transaction is read-only (check TransactionSynchronizationManager.isCurrentTransactionReadOnly()), sending queries to a replica. Other multi-tenant designs use a schema per tenant or a tenant_id column with a Hibernate filter, trading isolation for cost.

Run the model below. It has the same three parts: a map of data sources (one H2 database per tenant), a thread-local lookup key, and a routing DataSource wrapper. Two concurrent "requests" for different tenants write to their own databases, and a missing tenant is rejected instead of silently using the wrong database.

Java A routing DataSource with one H2 database per tenant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each tenant's rows stay in its own database (note the counts), and requests for an unknown or missing tenant fail loudly. Spring's real class also supports a default target and tolerates lookup keys as enum values or strings, but the principle is exactly this.

Choosing between the three

Need Tool Careful about
A quick CRUD API over entities, internal use Spring Data REST Exposes your data model, needs security and projections
Users or groups from a directory Spring Data LDAP Mostly read-oriented, use LDAPS, test with embedded server
Per-tenant database or read replicas AbstractRoutingDataSource Set the key before the transaction, clear the thread-local

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Spring Data REST generate for a repository interface annotated with @RepositoryRestResource(path = "products")?

    Spring Data REST publishes the repository as a hypermedia REST resource with collection and item endpoints, paging, sorting and exported query methods, without a controller.
  2. 2. How do you stop a repository method, such as delete, from being available over HTTP in Spring Data REST?

    Marking a method with @RestResource(exported = false) removes it from the REST API. The same attribute on @RepositoryRestResource hides a whole repository.
  3. 3. In Spring Data LDAP, what does the @Entry annotation describe?

    @Entry gives the base location in the directory and the objectClass values, so Spring knows where to search and what type of entries map to the class.
  4. 4. Why must a servlet filter set the tenant key before a @Transactional method is called when using AbstractRoutingDataSource?

    determineCurrentLookupKey is called when a connection is requested. A transactional method gets its connection at the start, so the key must already be set.
  5. 5. What is the danger of forgetting to clear the tenant ThreadLocal after a request?

    Application servers reuse threads. A stale value means a later request can silently read or write another tenant's data, so always clear it in a finally block.

Summary

  • Spring Data REST publishes repositories as HAL/REST resources with paging, search methods and links. Hide what should not be public, add security, and use projections, because the data model becomes your API.
  • Spring Data LDAP maps directory entries with @Entry, @Id Name and @Attribute, and offers LdapRepository and LdapTemplate; use LDAPS and an embedded server for tests.
  • AbstractRoutingDataSource picks a target DataSource per call from determineCurrentLookupKey(), the foundation of multi-tenant and read/write-splitting setups.
  • Set the lookup key before the transaction starts and clear the thread-local in a finally block.
  • The same repository-style programming model covers relational, REST and directory data, but each store has its own limits.

Next: Spring Data Redis applies the repository style to a key-value store used for caching.