gpt4 book ai didi

java - Spring Boot - 具有额外列的多对多关系的分页

转载 作者:太空宇宙 更新时间:2023-11-04 09:47:38 25 4
gpt4 key购买 nike

在使用带有额外列的多对多关系时,我找不到一种干净简单的方法来进行分页。

我的模型看起来像这样:

我有一个用户和一个产品模型。每个用户可以消费n个产品。每次消费都将存储在一个额外的表中,因为我想存储额外的信息,例如日期等。我已经实现了如下模型并且它有效,但我希望将用户的消费作为可分页的而不是检索整个集合。实现这一目标的最佳方法是什么?

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

}

我希望能够调用诸如“getConclusionList(Page page)”之类的方法,该方法然后返回可分页。

希望你能帮助我!

提前谢谢您!

最佳答案

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

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

然后你可以简单地调用它

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

关于java - Spring Boot - 具有额外列的多对多关系的分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55218034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com