【问题标题】:Any way to use the `@Procedure` annotation without an entity?有什么方法可以在没有实体的情况下使用“@Procedure”注释?
【发布时间】:2020-04-08 22:45:09
【问题描述】:

所以我想要一个“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;
    }
}

【问题讨论】:

    标签: java spring stored-procedures spring-data-jpa spring-repositories


    【解决方案1】:

    如果您觉得可以,您可以使用您拥有的任何实体来代替 Void。那里提供的实体应该无关紧要。

    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.

    【讨论】:

    • 我们一直在讨论它,但最后,我们觉得使用不相关的实体有点像我们宁愿不接受的设计不一致。诚然,在这方面,我们可能有点迂腐。 :P
    • 如果您的系统中有某种BaseEntity,您可以尝试使用它。或者也许是 Spring 的 AbstractPersistable: docs.spring.io/autorepo/docs/spring-data-jpa/current/api/org/…
    • AbstractPersistable 不起作用,但使用我们的基本实体似乎可以。我想我也许可以把它卖给团队。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2022-12-22
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    相关资源
    最近更新 更多