1️⃣ When You DON'T Need Custom Queries (Let Spring Data Handle It)

Spring Data Neo4j supports projections, meaning you can use DTOs without writing custom Cypher queries.

✅ Solution: Interface-Based Projection

Instead of a CertificateDTO class, we create an interface that maps fields automatically:


public interface CertificateProjection {
    UUID getId();
    String getCommonName();
    String getIssuer();
    LocalDate getExpiryDate();
    boolean isRevoked();
}

Then, modify the repository without writing a custom query:


List<CertificateProjection> findAll();

Spring Data Neo4j automatically maps only these fields.

No need to write Cypher queries manually.


2️⃣ When You SHOULD Write Custom Queries

There are cases where custom queries are needed, even though they require extra effort:

  1. If relationships slow down queries (e.g., fetching Certificate also loads related nodes like CertificateAuthority).
  2. If you need to aggregate data (e.g., "how many certificates expire this month?").
  3. If you need custom filtering (e.g., "find only revoked certificates").

Example: Find Only Revoked Certificates (Custom Query)

@Query("MATCH (c:Certificate) WHERE c.revoked = true RETURN c")
List<Certificate> findRevokedCertificates();

Why?