无法在spring-data中写出正确的请求

时间:2018-06-05 00:38:59

标签: java spring spring-boot spring-data

我正在使用spring-boot,并且有这三个人:

实体AppUser

@Entity
@Data
@AllArgsConstructor @NoArgsConstructor
public class AppUser implements Serializable {

    @Id @GeneratedValue
    private Long id;
    @Column(unique = true)
    private String username;
    private String password;
    private String prenom;
    private String nom;
    private Long tel;
    private String cin;
    private String email ;
    @ManyToMany(fetch = FetchType.EAGER)
    private Collection<AppRole> roles = new ArrayList<>();


    @OneToMany(mappedBy = "appUser" )
    @Fetch(value = FetchMode.SUBSELECT)
    @JsonManagedReference(value="appuser-contrat")
    private Collection<Contrat> contrats = new ArrayList<Contrat>();



    public void addToContrats(Contrat contrat){
        this.contrats.add(contrat);
    }


}

实体合同

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Contrat implements Serializable{

        @Id @GeneratedValue
        private Long id;
        private Date dateDebut ;
        private Date dateFin ;
        private Long idDevloppeur;
        @ManyToOne
        @JoinColumn(name = "Id_Project")
        @JsonBackReference(value="projet-contrat")
        private Project project;

        @ManyToOne
        @JoinColumn(name = "Id_AppUser")
        @JsonBackReference(value="appuser-contrat")
        private AppUser appUser;


}

实体项目

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Project implements Serializable{

        @Id @GeneratedValue
        private long id;
        private String intitule;
        private String description;

        @OneToMany(mappedBy = "project" )
        @Fetch(value = FetchMode.SUBSELECT)
        @JsonManagedReference(value="projet-contrat")
        private Collection<Contrat> contrats  = new ArrayList<Contrat>();



        public void addToContrats(Contrat contrat){
                this.contrats.add(contrat);
        }



 }

这是我使用的映射:

-Ane_to_many介于AppUser和Contrat之间。

项目与Contrat之间的

-One_to_many。

因此Contrat位于AppUser和Project之间。

我正在尝试在存储库中编写请求以获取没有指定项目的AppUser列表。

我试过这个

@Query("select u from AppUser u inner join u.roles r inner join u.contrats c where r = :role and c.appUser not in (" +
            "select d.appUser from Contrat d where d.project = :project )")

所以我想获得没有这个项目的用户列表&#39;:project&#39;

但是我得到一个空列表,而我应该得到所有AppUsers的列表,就像在我的应用程序中一样,还没有任何appuser的项目。

知道怎么写这个请求吗?

1 个答案:

答案 0 :(得分:1)

首先,我假设spring-data-jpaHibernate作为基础impl。

我的HQL有点生疏,但这样的事情应该有效:

select u from AppUser u inner join u.roles r inner join u.contrats c where r = :role and not exists ( from c.project p where p != :project)

这是一篇好文章:http://www.codewrecks.com/blog/index.php/2010/03/09/power-of-hql-condition-on-a-collection/