JPQL查询多对多

时间:2020-03-04 10:47:36

标签: spring hibernate spring-data-jpa

我想编写JPQL查询,以获取ID值为“多对多”表的行。我有两节课:

@Entity
@Table(name = "farm")
@Getter
public class Farm {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "name")
    private String name;

    @ManyToOne()
    @NotFound(action = NotFoundAction.IGNORE)
    @JoinColumn(name = "customer_id", referencedColumnName = "id")
    private Customer customer;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "user_farm", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "farm_id"))
    private List<User> users = new ArrayList<>();
}

@Entity
@Table(name = "user")
@Getter
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(name = "email")
    private String email;

    @Column(name = "password")
    private String password;

    @ManyToMany(mappedBy = "users")
    private List<Farm> farms = new ArrayList<>();

    @Column(name = "is_admin")
    private Boolean isAdmin;
}

和一个存储库:

public interface FarmRepository extends JpaRepository<Farm, Long> {

    @Query("select f from Farm f join f.users u where u.id=:userId")
    List<Farm> findByUserId(@Param("userId") Long userId);
}

但是,我收到了这个休眠错误:

ERROR: column user2_.id does not exist

我如何正确编写jpql查询以使其起作用?

3 个答案:

答案 0 :(得分:0)

该错误提示查询已执行,但您的数据库表不包含id列。

  1. 转到您的application.properties文件,并将其添加以在控制台中查看SQL:

    spring.jpa.show-sql = true

    spring.jpa.properties.hibernate.format_sql = true

  2. 执行测试,看看是否生成了正确的SQL。

  3. 考虑谁创建您的数据库?自动创建hbm2ddl模式?液基?飞路? schema.sql?修复数据库表。

答案 1 :(得分:0)

我想我可能也有类似的问题。表名“ user”通常是保留的,您不能使用它。尝试将其重命名为“ person”或其他名称。可能会有所帮助。

https://stackoverflow.com/a/30157994/9890613

答案 2 :(得分:0)

据我所知,@ManyToMany需要双向关系,但在您的示例中它是单向关系。让我们看一下结构:

User:
Long id;
Farm:
Long id;
User_farm:
Long r_user_id;
Long r_farm_id;

因此@JoinTable必须是:

  @ManyToMany(cascade = CascadeType.ALL)
  @JoinTable(
      name = "USER_FARM",
      joinColumns = @JoinColumn(name = "r_user_id", referencedColumnName = "id"),
      inverseJoinColumns = @JoinColumn(name = "r_farm_id", referencedColumnName = "id"))
  private List<User> users;