【问题标题】:findAll clashes with findAll with CrudRepository in ProjectionsfindAll 在 Projections 中与带有 CrudRepository 的 findAll 发生冲突
【发布时间】:2018-11-29 17:45:18
【问题描述】:

登录

@ApiModel
@Entity
public class Login {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private LocalDateTime loginDateTime;

    /** Other fields ***/
} 

仅登录日期

interface LoginDateOnly {

    @Value("#{target.loginDateTime.toLocalDate()}")
    LocalDate getDateFromLoginDateTime();

}

登录库

@RepositoryRestResource(collectionResourceRel = "login", path = "login")
public interface LoginRepository extends PagingAndSortingRepository<Login, Long> {

    Collection<LoginDateOnly> findAll();

    /** Other query methods **/
}

我只想获取所有我的登录记录,其中 LocalDate 部分 使用http://host/api/login 选择/投影我的loginDateTime。但目前我遇到了与 CrudRepository 的 findAll() 的冲突。如何使用投影尽可能解决这个问题。我将@Query 和@NamedQuery 作为我的最后手段。

【问题讨论】:

  • 你必须写@Query("Select * from Login")

标签: jpa spring-data-jpa spring-data-rest


【解决方案1】:

findAll 方法签名是:

List<T> findAll();

如果你想覆盖它,你不能使用另一个签名。

您只需要为此定义另一种方法即可获取投影列表,例如:

Collection<LoginDateOnly> findAllBy();

但我可以看到您使用的是 Spring Data REST,因此在这种情况下您不需要定义新方法。您应该首先在投影中添加注释@Projection

@Projection(name = "loginDateOnly", types = Login.class)
interface LoginDateOnly {
    //...
}

然后在请求的url中使用它的名字:

GET http://host/api/login?projection=loginDateOnly

在文档中查看更多信息:Projections and Excerpts

【讨论】:

  • 谢谢你,但仍然试图弄清楚为什么仍然返回其他属性并且只返回 loginDate
  • @LemuelNabong 检查投影的名称(在 @Projection 注释中)和请求中。他们必须匹配..
  • 完全一样,顺便说一句,我使用的是 spring-boot-starter-parent 1.5.4.RELEASE
  • @LemuelNabong 没关系。尝试进行另一个更简单的投影,例如仅使用getId()。并开启 Hibernate sql logging...
  • 我需要将 LoginDateOnly 放在与 Login 相同的包上,或者根据 stackoverflow.com/questions/30220333/… 答案通过 RepositoryRestConfiguration.projectionConfiguration().addProjection(...) 手动注册投影
猜你喜欢
  • 1970-01-01
  • 2015-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多