Search code examples
javaspringstored-proceduresspring-data-jpaspring-repositories

Any way to use the `@Procedure` annotation without an entity?


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;
    }
}

Solution

  • 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.