简体   繁体   English

Spring Boot-使用额外的列进行多对多关系分页

[英]Spring Boot - Pagination for Many-to-Many Relationship with extra Column

I can't find a clean and simple way to do pagination when using a many-to-many relationship with an extra column. 将多余的列与多对多关系时,我找不到一种干净而简单的分页方法。

My model looks like that: 我的模型如下所示:

I have a user and a product model. 我有一个用户和一个产品模型。 Each user can consume n products. 每个用户可以消费n种产品。 Each consumption will be stored in an extra table, because I want to store extra information such as date etc. I have implemented the model as follows and it works, but I want to get the consumptions of an user as a Pageable rather than retrieving the whole set. 每次消费将存储在一个额外的表中,因为我想存储额外的信息(例如日期等)。我已经按如下方式实现了该模型,并且可以正常工作,但是我希望将用户的消费作为Pageable来获取,而不是检索整套。 What would be the best way to implement that ? 实施该方法的最佳方法是什么?

@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;
    }
}

This is my class to store consumptions. 这是我的课程,用来存储消费。

@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());
    }

}

And this is my composite Primary Key which. 这是我的复合主键。

@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;
    }

}

I would like to be able to call a method such as "getConsumptionList(Page page)" which then returns a Pageable. 我希望能够调用诸如“ getConsumptionList(Page page)”之类的方法,然后该方法返回一个Pageable。

I hope you can help me! 我希望你能帮帮我!

Thank you in advance! 先感谢您!

I finally found a solution for my problem thanks to @mtshaikh idea: 由于@mtshaikh的想法,我终于找到了解决我问题的方法:

Just implement a Paginationservice: 只需实现一个分页服务:

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());

    }

Well, if using Spring Boot you could use a Repository: 好吧,如果使用Spring Boot,则可以使用存储库:

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

Then you can simply call it 那你可以简单地称它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 休眠中带有多列的多对多关系 - Many-to-Many Relationship in Hibernate with Extra Column 与复合键的多对多关系,Hibernate中的额外列 - Many-to-many relationship with composite keys, extra column in Hibernate 使用Spring Boot将数据插入到关系表中(多对多) - Insert data into relationship table (many-to-many) with Spring boot Spring 和 JPA 2.0 - 与额外列的多对多关系中的复合键 - Spring and JPA 2.0 - Composite key in many to many relationship with extra column Spring-JPA。多对多额外列 - Many-To-Many extra columns Spring JPA 多对多带有额外的列(休眠4) - Many-to-Many with extra column (Hibernate 4) 多对多Spring Data JPA关系中的额外列,变化很小 - Extra columns in many-to-many Spring Data JPA Relationship with minimal changes Spring 启动 JPA,数据不保存在多对多关系的连接表中 - Spring Boot JPA, data do not persist in join table of many-to-many relationship 使用 Spring Boot 和 Hibernate 在 2 个微服务之间建立多对多关系的问题 - Problems making a many-to-many relationship work across 2 microservices using Spring Boot & Hibernate JPA 具有相同数据库和额外属性的多对多关系 - JPA Many-To-Many Relationship with same DB and extra Attribute
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM