【问题标题】:Cannot compile interface-based projection in spring春季无法编译基于接口的投影
【发布时间】:2017-12-05 08:11:59
【问题描述】:

我有一个实体:

@Entity
class Person {

    @Id
    @GeneratedValue
    private Long id;
    private String firstname, lastname;
    private int age;

    public Person() {
    }
    //getters and setters

还有一个投影界面:

public interface NamesOnly {

    String getFirstname();
    String getLastname();
}

投影中的方法名称与实体类中的getter完全相同。

我的仓库:

public interface PersonRepository extends JpaRepository<Person, Long> {

    List<NamesOnly> findAll();   
}

我无法编译它。

test/projectiontest/PersonRepository.java:[20,21] findAll() in test.projectiontest.PersonRepository clashes with findAll() in org.springframework.data.jpa.repository.JpaRepository
return type java.util.List<test.projectiontest.projection.NamesOnly> is not compatible with java.util.List<test.projectiontest.Person>  

https://docs.spring.io/spring-data/jpa/docs/2.0.2.RELEASE/reference/html/#projections

我做错了什么?

【问题讨论】:

  • 您正在使用findAll,它已经在CrudRepository 中定义了一个特定的签名。你的不符合那个。你需要另一个方法名。
  • @M.Deinum ok,例如List&lt;NamesOnly&gt; findById(Long id); 工作正常,但是如何使用投影接口实现findAll
  • 定义自定义方法...

标签: spring spring-data-jpa


【解决方案1】:

好吧,正如@M.Deinum 在 cmets 中提到的,我不能使用findAll,因为它已经在JpaRepository 中定义。 我没有使用投影接口,而是编写了 DTO 类:

public class NamesOnlyDto {

    private String firstname, lastname;

    public NamesOnlyDto(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    public String getFirstname() {
        return firstname;
    }

    public String getLastname() {
        return lastname;
    }    
}

然后我可以像这样在我的存储库中使用它:

@Query("SELECT new test.projectiontest.projection.NamesOnlyDto(p.firstname, p.lastname) FROM Person p")
List<NamesOnlyDto> findEveryone();

它工作正常。我很确定这是一种解决方法,并且有一种方法可以通过投影界面解决这个问题,所以我没有回答这个问题。我希望其他人提供更好的解决方案。

【讨论】:

    【解决方案2】:

    使用FindAllProjectedBy() 而不是findAll()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      • 2019-02-26
      • 1970-01-01
      相关资源
      最近更新 更多