如何 select ManyToMany 关系为空或 null 的所有行

How to select all rows where ManyToMany relationship is empty or null

我有两个类

@Entity
public class Program {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private Long id;

      @ManyToMany
      @JoinTable(name = "program_roles",
        joinColumns = @JoinColumn(name = "program_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "program_role_id", referencedColumnName = "id"))
      private Set<ProgramRole> programRoles;

}

@Entity
public class ProgramRole {
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private Long id;
}

我想编写 JPA 查询以选择 programRoles 为空或 null 的所有程序。

您可以使用 JpaRepositoryProgram, Long 来实现您的要求。 以下应该有效:

@Repository
public interface ProgramRepository extends JpaRepository<Program, Long> {
        List<Program> findByProgramRolesIsEmpty();
    }

此方法将 return 所有具有空 Set<ProgramRole> 的程序实体,这至少对于空或空 Set

是正确的