7

So I'd like a "Void-Repository" through which to gain access to stored procedures that are not necessarily operation on entities.

@Repository
public interface StoredProceduresRepository extends CrudRepository<Void, Long> {

    @Procedure("my_answer_giver")
    String getMyAnswer(@Param("input") String input);
}

But that does, of course, not work because the CrudRepository expects Void to be an entity.

Is there a way to use the @Procedure annotation without having to create dummy entities or am I stuck with an implemented class that makes use of the EntityManager to query via prepared statements?

Because let's be honest, that's fugly:

@Repository
public class StoredProceduresRepository {

    @PersistenceContext
    EntityManager em;

    public String getMyAnswer(String input) {
        Query myAnswerGiver = em
            .createStoredProcedureQuery("my_answer_giver")
            .registerStoredProcedureParameter("input", String.class, ParameterMode.IN)
            .setParameter("input", input);
        Object result = ((Object[]) myAnswerGiver.getSingleResult())[0];
        return (String) result;
    }
}
User1291
  • 7,664
  • 8
  • 51
  • 108

1 Answers1

4

If it is ok for you you can use any Entity you have, in place of this Void. The Entity provided there should not matter.

public interface StoredProceduresRepository extends JpaRepository<SomeUnrelatedEntity, Long> {

        @Procedure("my_answer_giver")
        String getMyAnswer(@Param("input") String input);

}

I have been using it like this with database views.

Robert Niestroj
  • 15,299
  • 14
  • 76
  • 119
  • We have been discussing it, but in the end, we feel that using an unrelated entity is a bit of a design inconsistency that we would rather not live with. Granted, we may be a bit pedantic, in that regard. :P – User1291 Dec 16 '19 at 13:23
  • 2
    If you have some kind of `BaseEntity` in your system you could try tu use that. Or maybe Spring's `AbstractPersistable`: https://docs.spring.io/autorepo/docs/spring-data-jpa/current/api/org/springframework/data/jpa/domain/AbstractPersistable.html – Robert Niestroj Dec 16 '19 at 13:28
  • `AbstractPersistable` doesn't work, but using our base entity seems to. Think I may be able to sell that to the team. Thank you. – User1291 Dec 16 '19 at 16:38
  • Did you create a dummy entity? – Aldo Inácio da Silva Jun 23 '22 at 18:42