Gevorg Harutyunyan
Gevorg Harutyunyan

Reputation: 431

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

I have two classes

@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;
}

I would like to write JPA query for selecting all Programs where programRoles is empty or null.

Upvotes: 1

Views: 654

Answers (1)

Daniel Rafael Wosch
Daniel Rafael Wosch

Reputation: 1084

You can use a JpaRepository of Program, Long to achieve your requirement. The following should work:

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

This method will return all Program entities with an empty Set<ProgramRole> which at least is true for empty or null Set

Upvotes: 4

Related Questions