Create a Spring repository without an entity
Codemia Knowledge Hub ·
A Spring Data JPA repository is built around an entity type and its identity, so creating one with no entity is usually the wrong abstraction. If your use case has no entity, write a custom repository class using JdbcTemplate or NamedParameterJdbcTemplate, or a query-oriented service that returns DTOs.
Why JPA repositories expect entities
A typical Spring Data repository looks like this:
The User entity is central. The repository API exists to persist and query entities or aggregate roots, not arbitrary result sets with no domain type behind them. Wanting JpaRepository<?, ?> with no entity usually means the design should change rather than be hacked around.
A JdbcTemplate repository for query-only access
For repository-style access to rows without a JPA entity, JdbcTemplate is usually the better fit:
This suits data that is read-only or shaped for reporting rather than for entity lifecycle management.
Mapping results to DTOs
You can still map results into meaningful types instead of returning raw Object[] values:
You get typed data without pretending the result set is a JPA-managed entity.
A repository-style interface without Spring Data
An interface still helps organize the code, even when Spring Data does not generate it:
Provide your own implementation class. Be clear in naming whether a data-access class is JPA-backed or custom.
When you do need an entity
If the object:
- is persisted over time
- has identity
- participates in updates and relationships
then it probably should be an entity, and avoiding one usually produces a worse design than modeling it properly. The real question is not "how do I make Spring Data ignore entities" but "is this an entity use case or a query use case". Choose the persistence abstraction from the shape of the problem, not from the word "repository".
Related reading
- Create the perfect JPA entity
- Create two threads, one display odd other even numbers
- Create zip file from byte
- Creating a logical exclusive or operator in Java
- Creating a new empty branch for a new project
- Creating folders inside a GitHub repository without using Git
- Creating a topic for Apache Kafka 0.9 Using Java
- Creating an array of objects in Java
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.