使用JPA语法时,具有复杂键类的JpaRepository验证失败,并显示错误“方法查询验证失败”

时间:2019-06-18 10:37:49

标签: java spring-boot jpa jpa-2.1

我正在尝试使用JPA的“即用型”功能,并将数据从DB获取到对象。当JpaRepository使用简单的类作为键时,它是完美的,但是对于测试类,当键类有点复杂时,即使对于最简单的查询,jpa验证也会失败。

使用native_query = true可以解决此问题,但是我不确定自己做错了什么以及缺少什么。

MyTestPK.java:

package com.mytest.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Embeddable;
import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public class MyTestPK implements Serializable {
    private String type;
    private String name;
}


MyTest.java:

package com.mytest.model;

import lombok.Data;

import javax.persistence.*;

@Entity
@Table(name = "my_test")

@Data
@IdClass(MyTestPK.class)
public class MyTest {
    @Id
    @Column(name = "my_test_type", nullable = false)
    private String type;

    @Id
    @Column(name = "my_test_name", nullable = false)
    private String name;

    @Column(name = "my_test_misc")
    private String misc;
}

MyTestRepository.java:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface MyTestRepository extends JpaRepository<MyTest, MyTestPK> {
    @Query(value="SELECT m FROM MyTest m")
    List<MyTest> getAllObjs();
}

出现以下错误: ....  调用init方法失败;嵌套的异常是java.lang.IllegalArgumentException:方法公共抽象java.util.List的查询验证失败 com.mytest.dao.MyTestRepository.getAllObjs()!     在org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)〜[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]中     在org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)〜[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]

1 个答案:

答案 0 :(得分:0)

您可以使用@EmbeddedId,而无需再次在实体类中定义列。

MyTestPK.java:

package com.mytest.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Embeddable;
import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public class MyTestPK implements Serializable {
    @Column(name = "my_test_type", nullable = false)
    private String type;
    @Column(name = "my_test_name", nullable = false)
    private String name;
}

MyTest.java:

package com.mytest.model;

import lombok.Data;

import javax.persistence.*;

@Entity
@Table(name = "my_test")
@Data
public class MyTest {
    @EmbeddedId
    private MyTestPK pk;

    @Column(name = "my_test_misc")
    private String misc;
}