Spring数据异常查询

时间:2017-05-31 17:12:23

标签: java spring-data

我遇到弹簧数据查询问题。我想接收用户已赋予角色的用户(列表)(角色在列表中),此用户(列表)的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 个答案:

答案 0 :(得分: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