gpt4 book ai didi

java - hibernate 时内存不足

转载 作者:行者123 更新时间:2023-12-02 00:19:16 26 4
gpt4 key购买 nike

嗨,我在 hibernate 中创建了多对一关系。以下是相关代码。

B 表中有数千条记录,它链接到表 A 的单个记录。当我使用 getBList() 方法时,它将返回数千条记录,并且 JAVA 内存不足。那么我该如何解决这个问题。

@Entity
@Table(name = "A")
public class A {

private int Id;
private String aName;
private List<MksReleaseInfo> bList;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
public int getId() {
return releaseId;
}

public void setId(final int Id) {
this.Id = Id;
}

@Column(name = "aname", unique = true)
public String getAName() {
return aName;
}

public void setAName(final String aName) {
this.aName = aName;
}
@OneToMany(mappedBy = "aName")
public List<MksReleaseInfo> getBList() {
return bList;
}

public void setBList(final List<B> bList) {
this.bList = bList;
}
}


@Entity
@Table(name = "B")
public class B {

private int bIndex;
private int bpriority;
private A aName;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
protected int getBIndex() {
return mksReleaseInfoIndex;
}

protected void setBIndex(final int bIndex) {
this.bIndex = bIndex;
}

@Column(name = "priority")
public int getBPriority() {
return bpriority;
}

public void setBPriority(final int bpriority) {
this.bpriority = bpriority;
}

@ManyToOne
@JoinColumn(name = "Id")
public A getAName() {
return aName;
}

public void setAName(final A aName) {
this.aName = aName;
}
}

在所有评论之后我已经实现了以下代码。但它再次给出内存不足。我是否应该显式刷新内存以及如何刷新?

public List<B> getList(String name, int offset, int limit) throws DAOException {
try {
String hql = "from B where name = :name";
begin();
Query query = getSession().createQuery(hql);
query.setString("name", name);

if(offset > 0){
query.setFirstResult(offset);
}

if(limit > 0){
query.setMaxResults(limit);
query.setFetchSize(limit);
}
commit();
return query.list();
} catch (HibernateException e) {
rollback();
}
}

public Long countB(String name) throws DAOException {
try {
String hql = "select count(*) from B where name = :name";
begin();
Query query = getSession().createQuery(hql);
query.setString("name", name);
commit();
return (Long)query.uniqueResult();
} catch (HibernateException e) {
rollback();
}
}


long count = countB(name);
int counter = (int) (count / 200);
if(count%200 > 0){
counter++;
}
for(int j = 0;j<counter;j++){
lists = getList(name, j*200, 200);

for(B count1 : lists){
System.out.println(count1);
}
}

最佳答案

您可以引入一个 DAO,以便以分页方式从给定 A 对象的 B 检索记录。

例如:

public interface BDao {

Page findByA(A a, PageRequest pageRequest);

}

也许您可以从Spring Data中采取的方法中得到一些想法。

关于java - hibernate 时内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11356851/

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