1

在非事务环境中,可以在 Hibernate 中批量删除多行,如下所示。

Session session=HibernateUtils.getSessionFactory().getCurrentSession();
session.beginTransaction();

String temp[]=request.getParameter("delIds").split(",");
int len=temp.length;
countryService.delete(temp);

Configuration configuration=new Configuration();
configuration.setProperty("hibernate.jdbc.batch_size", "50");

for(int i=0;i<len;i++)
{
    Country c=(Country)session.get(Country.class, new Long(temp[i]));

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

    session.delete(c);
}

//session.flush();
session.getTransaction().commit();

每批将考虑删除 50 行。


如何在交易环境中实现同样的目标?

@Service
@Transactional(readOnly = true, propagation=Propagation.REQUIRES_NEW)

final public class CountryDAO implements CountryService
{
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }

    @SuppressWarnings("unchecked")
    @Transactional(readOnly=false, propagation=Propagation.REQUIRES_NEW)
    public void delete(String[] id)
    {
        int len=id.length;
        Session session=sessionFactory.getCurrentSession();

        for(int i=0;i<len;i++)
        {
            Country country=(Country)session.get(Country.class, Long.valueOf(id[i]));
            session.delete(country);
        }
    }
}

这可行,但是如何删除一批中的行,每批都有特定的行,以便可以最小化流向数据库的流?


我可以这样做。

@SuppressWarnings("unchecked")
//@Transactional(readOnly=false, propagation=Propagation.REQUIRES_NEW)
public void delete(String[] id)
{
    int len=id.length;
    Session session=sessionFactory.openSession();       //<----------------
    Transaction transaction = session.beginTransaction();

    Configuration configuration=new Configuration();
    configuration.setProperty("hibernate.jdbc.batch_size", "50");

    for(int i=0;i<len;i++)
    {
        if(i%49==0)
        {
            session.flush();
            session.clear();
        }
        Country country=(Country)session.get(Country.class, Long.valueOf(id[i]));
        session.delete(country);
    }
    transaction.commit();
    session.close();
}

根据下面的答案。

4

1 回答 1

5

您可以使用在 HQL 中包含删除的“批量”更新命令。

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/batch.html#batch-direct

于 2012-12-12T20:36:10.617 回答