我正在使用spring 4.1.4.RELEASE + hibernate 4.3.6.Final,我有一个关于hibernate分页的问题,限制了OneToMany集合的大小,这里是代码:
create table product (
id int(6) unsigned auto_increment primary key,
name varchar(30)
);
create table picture (
id int(6) unsigned auto_increment primary key,
product_id varchar(30),
url varchar(30)
);
@Entity(name = "product")
public class Product extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "product")
private List<Picture> pictures;
public List<Picture> getPictures() {
return pictures;
}
public void setPictures(List<Picture> pictures) {
this.pictures = pictures;
}
}
@Entity(name = "picture")
public class Picture extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "url")
private String url;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "product_id", referencedColumnName = "id")
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
产品和图片之间的关系是OneToMany,现在我想要的是获取产品列表并将每个产品的图片大小限制为2,我怎样才能实现这一目标?
我已经尝试过BatchSize,但它似乎无法正常工作,即使这样可行,如果我想要的话,无论BatchSize如何,我都能获得所有结果吗?
有人说只有先查找产品清单,然后找每个产品的2张图片,这是唯一的方法吗?答案 0 :(得分:0)
理想情况下,Query.setMaxResults()应该解决问题,但有很多方法
您可以使用@Size
@OneToMany(fetch = FetchType.LAZY,mappedBy =“product”) @Size(min = 1,max = 2) 私人列表图片;
还有@BatchSize
@OneToMany(fetch = FetchType.LAZY,mappedBy =“product”) @BatchSize(大小= 2) 私人列表图片;
如果仍然无效,我们可以在逐个查询的帮助下进行原生查询