简体   繁体   中英

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. 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. 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.

I hope you can help me!

Thank you in advance!

I finally found a solution for my problem thanks to @mtshaikh idea:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM