【问题标题】:How to execute a stored procedure with JPA's crudrepository with Spring boot?[PropertyReferenceException]如何使用 JPA 的 crudrepository 和 Spring boot 执行存储过程?[PropertyReferenceException]
【发布时间】:2018-03-14 09:43:03
【问题描述】:

我尝试执行如下所示的 postgres 存储过程:

CREATE OR REPLACE FUNCTION get_subjects()
RETURNS SETOF subject AS
$$
SELECT * FROM subject;
$$
LANGUAGE 'sql';

我有一个用于主题、存储库和服务的 POJO 类,定义如下:

@Entity
@Table(name = "subject")
@NamedStoredProcedureQueries({
        @NamedStoredProcedureQuery(name = "get_subjects",
                procedureName = "get_subjects")
})
public class Subject {

    @Id
    @Column(name = "uid")
    @Type(type = "pg-uuid")
    private UUID uid;
    private String name;
    private String start_date;
    private String end_date;

    protected Subject(){

    }

    public Subject(UUID uid, String name, String start_date, String end_date) {
        this.uid = uid;
        this.name = name;
        this.start_date = start_date;
        this.end_date = end_date;
    }

    //getter setter

@Repository
public interface SubjectRepository extends CrudRepository<Subject, Long> {

    @Procedure(name = "get_subjects")
    Collection<Subject> retrieveSubjects();
}


@Service
public class SubjectService {

    private final SubjectRepository subjectRepository;

    @Autowired
    public SubjectService(SubjectRepository subjectRepository) {
        this.subjectRepository = subjectRepository;
    }

    public Collection<Subject> getAllSubjects(){
        return subjectRepository.retrieveSubjects();
    }
}

导致的错误:

org.springframework.data.mapping.PropertyReferenceException: 否 找到类型主题的属性retrieveSubjects!

我尝试实现一个 SubjectRepositoryCustom,我在 Collection&lt;Subject&gt; 上得到了一个空指针。我浏览了一些教程,例如https://dzone.com/articles/calling-stored-procedures-from-spring-data-jpa。 我还有一个存储过程在我的另一个存储库上运行,我在其中插入了一个存储过程,效果很好。

有人能指出导致错误的原因并给出示例解决方案吗?

【问题讨论】:

  • 一切看起来都不错,您使用的是什么版本的 spring-data-jpa? JPA 中的调用过程也在 2.1 中引入。顺便说一句,您的 id 是 UUID 类型,但在您的存储库中它是 Long

标签: java jpa spring-boot stored-procedures


【解决方案1】:

对于您的 retrieveSubjects 方法,您可以使用 CrudRepository 中的 findAll()。在这种简单的情况下,不需要 get_subjects() 过程。参见https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html的第一个示例

对于我使用 nativeQuery 并让 Spring 正确映射结果的过程。

@Repository
public interface MyRepository extends CrudRepository<MyModel, Long> {

    @Query(value = "CALL my_procedure()", nativeQuery = true)
    List<MyModel> myProcedure();
}

如果您的过程检索一些计算/自定义行,请确保它检索每行中 @Id 变量的唯一值。我在自定义过程结果中使用了错误的 @Id 列时遇到了映射问题,并最终使用了一个带有未使用的主键自动递增列的临时表。

【讨论】:

    猜你喜欢
    • 2015-06-19
    • 2015-11-25
    • 2017-07-04
    • 1970-01-01
    • 2014-07-01
    • 2018-05-12
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多