2017-05-31 82 views
1

我對春季數據查詢有問題。我想要接收用戶已賦予角色的用戶(列表)(角色在列表中)並且此用戶(列表)的assignedOrders爲空或此訂單處於給定狀態(State爲枚舉類)。春季數據異常查詢

我想出了這樣的查詢:

List<User> findAllByRoleContainsAndOrdersAssignedStateIsNullOrOrdersAssignedStateEquals(State state,Role role); 

,但它並不在所有的工作。這是複雜的,我從來沒有創建過這樣的查詢。你能幫助我嗎?非常感謝 !

編輯: 的一段代碼:

@Entity 
public class User implements Persistable { 
........... 
@Column(name = "ROLES") 
@Enumerated(EnumType.STRING) 
@ElementCollection(targetClass = Role.class) 
private List<Role> role; 
.......... 
@OneToMany(fetch = FetchType.LAZY, mappedBy = "driver") 
private List<Order> ordersAssigned = new ArrayList<>(); 

} 
@Entity 
public class Order implements Persistable { 
........... 
@JoinColumn(name = "DRIVER_ID") 
@ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.PERSIST) 
private User driver; 

@Column(name = "STATE") 
@Enumerated(EnumType.STRING) 
private State state; 
............. 

} 
+1

我覺得最好使用'@ Query'。 – Alex78191

回答

1

嘗試是這樣的:

@Entity 
public class User { 

    private String name; 

    @ElementCollection 
    @Column(name = "role") 
    private List<Role> roles = new ArrayList<>(); 

    @OneToMany(mappedBy = "user") 
    private List<Order> orders = new ArrayList<>(); 

    public User(String name, Role... roles) { 
     this.name = name; 
     this.roles.addAll(asList(roles)); 
    } 

    public enum Role { 
     ROLE1, ROLE2 
    } 
} 

@Entity 
public class Order { 

    private String title; 

    @ManyToOne 
    private User user; 

    private State state; 

    public enum State { 
     STATE1, STATE2 
    } 
} 

public interface UserRepository extends JpaRepository<User, Long> { 

    @Query("select distinct u from User u join u.orders o join u.roles r where r = ?1 and (o.state is null or o.state = ?2)") 
    List<User> getUsers(User.Role role, Order.State state); 
} 

工作example

更多的信息是herehere

+0

有用戶包含訂單包含單個狀態的訂單列表。我需要用戶角色(角色列表中的一個)等於Role.DRIVER和assignedOrders(列表)爲空或訂單具有State.FINISHED的用戶。 – Unlucky

+1

@Unlucky請向您的問題添加您需要的方法和界面(簽名)。 – Cepr0

+0

對不起,它不完整。就是現在。 – Unlucky