首页 > 解决方案 > 有什么方法可以在没有实体的情况下使用“@Procedure”注释?

问题描述

所以我想要一个“Void-Repository”,通过它可以访问不一定对实体进行操作的存储过程。

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

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

但这当然行不通,因为它CrudRepository期望Void成为一个实体。

有没有一种方法可以使用@Procedure注释而不必创建虚拟实体,或者我是否坚持使用EntityManager通过准备好的语句进行查询的实现类?

因为老实说,这很丑陋:

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

标签: javaspringstored-proceduresspring-data-jpaspring-repositories

解决方案


如果对您来说没问题,您可以使用您拥有的任何实体来代替 this Void。那里提供的实体应该无关紧要。

public interface StoredProceduresRepository extends JpaRepository<SomeUnrelatedEntity, Long> {

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

}

我一直在将它与数据库视图一起使用。


推荐阅读