2

With Spring Data you can make a Repository for a given entity:

@Repository
public interface MyRepo extends CrudRepository<MyEntity, Long> {...}

But what if you have a lot of custom queries not tied to a specific Entity?

None of the below work:

@Repository
public interface MyRepo {...}
@Repository
public interface MyRepo extends CrudRepository {...}
@Component
public interface MyRepo extends Repository {...}

And so on..

Essentially what I want, is to be able to encapsulate some @Querys into an injectable class or interface.

3
  • Think this link will help you. Commented Mar 26, 2020 at 16:43
  • 1
    Not sure how that link relates. Commented Mar 26, 2020 at 21:41
  • Does this answer your question? Create spring repository without entity Commented Feb 21, 2024 at 9:23

1 Answer 1

4

You can use a generic entity superclass instead of a concrete entity. It's very usual to have an abstract superclass to declare the id of the entities or other common stuff.

@MappedSuperclass
public abstract class AbstractEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }   
}

Then you can create a repository like this and autowire where you need it:

public interface MyRepo extends JpaRepository<AbstractEntity, Long> {

    @Query("...")
    myQueryMethod();
}

That said, Spring Data interfaces are designed to work with a root entity. I think that if you want to avoid it, you should use the underlying JPA layer (that is, use the EntityManager to execute queries instead of a Spring Data Repository).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.