【问题标题】:How to perform a query in Spring Data /JPA with a foreign Key?如何使用外键在 Spring Data /JPA 中执行查询?
【发布时间】:2018-09-24 16:03:37
【问题描述】:

我有一个问题,我需要使用表中的外键执行查询。问题是在上面的@Query(在上面的 ExpenseRepository 中制作)我的日志说他不是按用户 ID(外键)搜索,而是在搜索费用实体类的主键。

这是我的用户实体类:

@Entity
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String email;

    @NotBlank(message = "Password required")
    @Size(min = 6)
    private String password;

    //getters and setters

这是我的费用实体类:

@Entity
public class Expenses implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private long limitValue;
    private long spentValue;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "id")
    private User user;

    //getters and setters here

最后,这是我自己进行查询的存储库

public interface ExpensesRepository extends JpaRepository< Expenses, Long> {


    @Query("FROM Expenses g where g.id = :userId")
    GestaoGastos findAllByCurrentUser(@Param("userId") Long userId);

}

【问题讨论】:

  • JPQL 以SELECT {alias} 开头。此外,您不能在 PK 和“用户”字段之间共享一些“id”列(特别是因为两者都是自动生成的)。
  • 是的,但我想通过 userId 查询用户,以便仅获取属于已登录用户的信息。所以我需要这个查询,你对如何解决这个问题有任何想法吗?如果plz你能用代码告诉我你在说什么吗?关于 SELECT{alias} 不是强制使用它,spring data 将其识别为只有 FROM 语句的选择:)
  • 必须使用“SELECT {alias}”;如果您不准备接受我的话,请阅读 JPA 规范 - 如果您愿意并且不可移植,请您将 JPA 规范混为一谈。 g.id 在您的查询中是 Expenses.id,这是费用的“id”列 ... PK。如前所述,您不能与映射到不同类中某个自动生成字段的关系共享该列。

标签: java mysql spring jpa spring-data


【解决方案1】:

使用字段,而不是 @Query 中的列

public interface ExpensesRepository extends JpaRepository< Expenses, Long> {
    @Query("FROM Expenses g where g.user.id = :userId")
    GestaoGastos findAllByCurrentUser(@Param("userId") Long userId);
}

【讨论】:

  • 是的,这就是问题所在。我认为这是问题所在。感谢您的反馈。
【解决方案2】:

您可以像这样在存储库类中添加一个方法:

public interface ExpensesRepository extends JpaRepository< Expenses, Long> {
    GestaoGastos findAllByUserId(Long userId);
}

【讨论】:

  • 它也可以完成这项工作,但问题是,即使 userId 存在于费用表中,它也会生成不必要的“左外连接”。
猜你喜欢
  • 1970-01-01
  • 2021-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
  • 2017-10-09
  • 2014-12-02
相关资源
最近更新 更多