对外键排序请求时避免JOIN

时间:2017-11-23 10:03:28

标签: spring-mvc jpa spring-boot

我正在开发一个Spring REST Web服务,我有一个带有外键的表和以下实体:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@EqualsAndHashCode(exclude = "id")
public class Foo {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

    @OneToOne
    @NotNull
    private FooBar fooBar;

    public static Foo fromFooBar(FooBar fooBar) {
        return builder()
                .fooBar(fooBar)
                .build();
    }
}

这是我的回购:

public interface FooRepository extends JpaRepository<Foo, Long>, QueryDslPredicateExecutor<Foo> {
}

我的服务:

@Service
@Slf4j
public class FooService {

    @Autowired
    private FooRepository repository;

    public Page<Foo> findAll(Predicate predicate, Pageable pageable) {
        return repository.findAll(predicate, pageable);
    }
}

我的控制员:

@Slf4j
@RestController
@RequestMapping("/api/foo")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FooController {

    private final FooService service;

    @RequestMapping
    public Page<Foo> findAll(@QuerydslPredicate(root = Foo.class) Predicate predicate, Pageable pageable) {
        return service.findAll(predicate, pageable);
    }
}

当我对外键api/foo?sort=fooBar_id,ASC请求排序时,请求JOIN数据库:

select foo.id as id, foo.fooBar_id as fooBarId from foo left outer join fooBar on foo.fooBar_id=fooBar.id order by fooBar.id asc limit ?

有没有办法避免这种JOIN?只需按外键排序?

0 个答案:

没有答案