Springdata JPA存储库findAllByXXX()返回null而不是一个空列表

时间:2019-02-25 03:42:03

标签: spring-boot spring-data-jpa

我正在使用springboot 2.1.2,我在存储库中遇到一些问题。 这是我的实体类:

@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "orders")
public class Order {
    @Id
    @GeneratedValue
    private long id;

    @ManyToOne(targetEntity = User.class)
    private User user;

    //other fields and getters and setters are ignored
}

@Entity
@Getter
@Setter
@NoArgsConstructor
public class User {

    @Id
    private String email;

    //other fields and getters and setters are ignored
}

我的OrderRepository:

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {

    @Query("select o from Order o where o.user.email = ?1")
    List<Order> findAllByUserId(String userId);

    List<Order> findAllByUser(User user);
}

当我调用findAllByUserId或findAllByUser时,存储库返回一个空值而不是一个空列表,这很奇怪,因为我确定数据库中有数据

我已经阅读了其他类似的问题,但它们似乎无济于事。

我尝试用调试器解决问题,并且进入 AsyncExecutionInterceptor类

@Nullable
public Object invoke(MethodInvocation invocation) throws Throwable {
    Class<?> targetClass = invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null;
    Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
    Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
    AsyncTaskExecutor executor = this.determineAsyncExecutor(userDeclaredMethod);
    if (executor == null) {
        throw new IllegalStateException("No executor specified and no default executor set on AsyncExecutionInterceptor either");
    } else {
        Callable<Object> task = () -> {
            try {
                Object result = invocation.proceed();
                if (result instanceof Future) {
                    return ((Future)result).get();
                }
            } catch (ExecutionException var4) {
                this.handleError(var4.getCause(), userDeclaredMethod, invocation.getArguments());
            } catch (Throwable var5) {
                this.handleError(var5, userDeclaredMethod, invocation.getArguments());
            }

            return null;
        };
        return this.doSubmit(task, executor, invocation.getMethod().getReturnType());
    }
}

我注意到,在此方法的第13行中,变量结果是具有适当Order对象的List,但是if子句失败并因此返回空值。

那么有人知道如何解决问题吗?

================================================ ===========

为了更加清楚,我将显示数据库模式:

all tables names orders table structure user table structure

这是Hibernate生成的sql:

Hibernate: select order0_.id as id1_8_, order0_.address_id as address_6_8_, order0_.date as date2_8_, order0_.deliver_time as deliver_3_8_, order0_.restaurant_id as restaura7_8_, order0_.status as status4_8_, order0_.total as total5_8_, order0_.user_email as user_ema8_8_ from orders order0_ where order0_.user_email=?
Hibernate: select address0_.id as id1_1_0_, address0_.location as location2_1_0_, address0_.name as name3_1_0_, address0_.phone as phone4_1_0_, address0_.user_email as user_ema5_1_0_, user1_.email as email1_14_1_, user1_.password as password2_14_1_, user1_.pts as pts3_14_1_, user1_.status as status4_14_1_, user1_.user_name as user_nam5_14_1_ from address address0_ left outer join user user1_ on address0_.user_email=user1_.email where address0_.id=?
Hibernate: select restaurant0_.id as id1_9_0_, restaurant0_.email as email2_9_0_, restaurant0_.location as location3_9_0_, restaurant0_.name as name4_9_0_, restaurant0_.password as password5_9_0_, restaurant0_.phone as phone6_9_0_, restaurant0_.status as status7_9_0_, restaurant0_.type as type8_9_0_, restaurant0_.vcode as vcode9_9_0_ from restaurant restaurant0_ where restaurant0_.id=?
Hibernate: select address0_.id as id1_1_0_, address0_.location as location2_1_0_, address0_.name as name3_1_0_, address0_.phone as phone4_1_0_, address0_.user_email as user_ema5_1_0_, user1_.email as email1_14_1_, user1_.password as password2_14_1_, user1_.pts as pts3_14_1_, user1_.status as status4_14_1_, user1_.user_name as user_nam5_14_1_ from address address0_ left outer join user user1_ on address0_.user_email=user1_.email where address0_.id=?

2 个答案:

答案 0 :(得分:0)

您的代码不明确。如果您想通过电子邮件获取订单列表,请像下面这样写。不需要@Query

public interface OrderRepository extends JpaRepository<Order, Long> {

    List<Order> findAllByUserEmail(String email);

}

和下面的实体类

我正在使用springboot 2.1.2,我在存储库中遇到一些问题。这是我的实体类:

@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "orders")
public class Order {
    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne(targetEntity = User.class)
    private User user;

    //other fields and getters and setters are ignored
}

@Entity
@Getter
@Setter
@NoArgsConstructor
public class User {

    @Id
    private Long userId;
    private String email;

    //other fields and getters and setters are ignored
}

答案 1 :(得分:0)

您的OrderRepository界面中的以下方法签名应该起作用:

List<Order> findByUser_UserEmail(String email);

此外,您可以添加下一个:

@Query("select o from Order o join User u where u.email = :email") List<Order> findAllByUserEmail(String email);

更新

尝试查询所有实体,尝试从存储库中执行findAll,如果它也是null,则在代码库或配置中也会遇到问题。


尝试更新您的类图定义:

public class Order {
    @ManyToOne
    @JoinColumn(name="user_email")
    private User user;

}

public class User {
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private Set<Order> orders;
}