首页 > 解决方案 > OutOfMemory 错误:超出 GC 开销限制 - 休眠

问题描述

我正在使用休眠将数据保存到我的表中。我有我的实体类和主类,通过主类我调用了实体类构造函数并构建对象,并在 for 循环中通过休眠将对象保存到 DB。我收到 OutofMemory 错误:超出 GC 开销限制,我不明白为什么,有人可以帮忙吗? 内存不足错误

这是我的代码:

Session session = HibernateSessionFactory.getSession();
for(int i=0;i<serviceIds.length;i=i++)
{
 EntityClass ec = new EntityClass
                            (Integer.parseInt(serviceIds[i]),0,someId3, 0,1,id2,
                            new Timestamp(System.currentTimeMillis()), 0,
                            null, null, 0, null,null,null,null);
session.save(ec);
}
session.flush();
session.clear();

这是我的实体类:

public class EntityClass implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    private Integer id;
    private Integer someId1;
    private Integer someId2;
    private Integer someId3;
    private Integer flag1;
    private Integer flag2;
    private Integer createdBy;
    private Timestamp createdDate;
    private Integer modifiedBy;
    private Timestamp modifiedDate;
    private Timestamp endDate;
    private Integer attribute1;
    private String attribute2;
    private String attribute3;
    private String attribute4;
    private String attribute5;
//full constructor
public EntityClass(Integer someId1, Integer someId2,
            Integer someId3, Integer funBlockFlag, Integer functionalFlag,
            Integer createdBy, Timestamp createdDate, Integer modifiedBy,
            Timestamp modifiedDate, Timestamp endDate, Integer attribute1,
            String attribute2, String attribute3, String attribute4,
            String attribute5) {
        this.someId1= someId1;
        this.someId2 = someId2;
        this.someId3 = someId3;
        this.funBlockFlag = funBlockFlag;
        this.functionalFlag = functionalFlag;
        this.createdBy = createdBy;
        this.createdDate = createdDate;
        this.modifiedBy = modifiedBy;
        this.modifiedDate = modifiedDate;
        this.endDate = endDate;
        this.attribute1 = attribute1;
        this.attribute2 = attribute2;
        this.attribute3 = attribute3;
        this.attribute4 = attribute4;
        this.attribute5 = attribute5;
    }
//getter and setters of all fields

谁能帮我解决这个问题?

标签: javaspringhibernatehql

解决方案


当我们持久化一个实体(在本例中EntityClass)时,Hibernate 会将它存储在持久化上下文中。

从您的情况来看,对于您为 JVM 设置的内存,serviceIds 的长度似乎太大了。

也许尝试刷新和清除每个 N 元素的持久性上下文。例如,假设您的 BATCH_SIZE 是 20

private static final BATCH_SIZE = 20; // declare at class level

Session session = HibernateSessionFactory.getSession();
for(int i=0;i<serviceIds.length;i=i++)
{
    EntityClass ec = new EntityClass
                            (Integer.parseInt(serviceIds[i]),0,someId3, 0,1,id2,
                            new Timestamp(System.currentTimeMillis()), 0,
                            null, null, 0, null,null,null,null);
    session.save(ec);

    if (i % BATCH_SIZE == 0) {
        session.flush();
        session.clear();
    }
}
session.flush();
session.clear();

推荐阅读