Spring Boot-通过多列进行分页以实现多对多关系

时间:2019-03-18 09:21:12

标签: java spring hibernate jpa

当对多列使用多对多关系时,我找不到一种干净而简单的分页方法。

我的模型如下:

我有一个用户和一个产品模型。每个用户可以消费n种产品。每次消费都会存储在一个额外的表中,因为我想存储额外的信息(例如日期等)。我已经按如下方式实现了该模型,并且可以正常工作,但是我想将用户的消费作为Pageable而不是检索整套。实现该目标的最佳方法是什么?

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(
            mappedBy = "user",
            cascade = CascadeType.ALL,
            orphanRemoval = true
    )
    private List<Consumption> consumptionList = new ArrayList<>(); // never set this attribute

    public List<Consumption> getConsumptionList() {
        return consumptionList;
    }


    public void addConsumption(Product product) {
        Consumption consumption = new Consumption(this, product);
        consumptionList.add(consumption);
        product.getConsumptionList().add(consumption);
    }

    public void removeConsumption(Consumption consumption) {
        consumption.getProduct().getConsumptionList().remove(consumption);
        consumptionList.remove(consumption);
        consumption.setUser(null);
        consumption.setProduct(null);
    }
}

-

@Entity
@NaturalIdCache
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(
            mappedBy = "product",
            cascade = CascadeType.ALL,
            orphanRemoval = true
    )
    private List<Consumption> consumptionList = new ArrayList<>();

    public List<Consumption> getConsumptionList() {
        return consumptionList;
    }
}

这是我的课程,用来存储消费。

@Entity
public class Consumption {

    @EmbeddedId
    private UserProductId id;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("userId")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @MapsId("productId")
    private Product product;

    public Consumption(User user, Product product) {
        this.user = user;
        this.product = product;
        this.id = new UserProductId(user.getId(), product.getId());
    }

}

这是我的复合主键。

@Embeddable
public class UserProductId implements Serializable {

    @Column(name = "user_id")
    private Long userId;

    @Column(name = "product_id")
    private Long productId;

    private UserProductId() {
    }

    public UserProductId(Long userId, Long productId) {
        this.userId = userId;
        this.productId = productId;
    }

}

我希望能够调用诸如“ getConsumptionList(Page page)”之类的方法,然后该方法返回一个Pageable。

希望你能帮助我!

提前谢谢!

2 个答案:

答案 0 :(得分:0)

由于@mtshaikh的想法,我终于找到了解决问题的方法:

只需实现分页服务:

public Page<Consumption> getConsumptionListPaginated(Pageable pageable) {
        int pageSize = pageable.getPageSize();
        int currentPage = pageable.getPageNumber();
        int startItem = currentPage * pageSize;

        List<Consumption> list;

        if (consumptionList.size() < startItem) {
            list = Collections.emptyList();
        } else {
            int toIndex = Math.min(startItem + pageSize, consumptionList.size());
            list = consumptionList.subList(startItem, toIndex);
        }

        return new PageImpl<>(list, PageRequest.of(currentPage, pageSize), consumptionList.size());

    }

答案 1 :(得分:0)

好吧,如果使用Spring Boot,则可以使用存储库:

@Repository
public interface ConsumptionRepo extends JpaRepository<Consumption, Long>{
    List<Consumption> findByUser(User user, Pageable pageable);
}

然后您可以简单地调用它

ConsumptionRepo.findByUser(user, PageRequest.of(page, size);