spring-data-jpa Springdata JPA存储库findAllByXXX()返回空值而不是空列表

kx5bkwkv  于 2022-11-10  发布在  Spring
关注(0)|答案(2)|浏览(200)

我使用的是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时,存储库返回一个null值而不是一个空列表,这很奇怪,因为我确信我的数据库有数据。
我读过其他类似的问题,它们似乎没有帮助。
我尝试使用调试器修复该问题,并跟踪到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子句失败,因此返回空值。
有人知道如何解决这个问题吗?

为了使它更清楚,我将显示我的db模式:
第一次
下面是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=?
jv4diomz

jv4diomz1#

你的代码是模棱两可的。如果你想通过电子邮件获得订单列表,那么就写如下。没有必要的@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
}
kmbjn2e3

kmbjn2e32#

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,则代码库或配置中存在一些问题。
请尝试更新类别Map定义:

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

}

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

相关问题