简体   繁体   English

使用hibernate持久化/更新数据集合到数据库中

[英]persist/update collection of data into database using hibernate

I am newbie to Hibernate framework and I am curious about the way persist and update work. 我是Hibernate框架的新手,我很好奇持久化和更新工作的方式。

Currently in my project when I would like to persist or update collection of data into database, I am doing it one by one via looping method. 目前在我的项目中,当我想将数据集合持久化或更新到数据库中时,我是通过循环方法逐个完成的。 For instance, 例如,

    public persistData(){
       List<Person> personList = new ArrayList<>();
       for(Person person : personList){
            session.persist(person);
       }
    }

Is it possible to, for example, 例如,是否有可能

    session.persist(personList);

Or there is anyway else I can persist/update collection of data at once without looping? 或者还有其他方面我可以一次性持久/更新数据集合而不循环?

Editted: I have found Hibernate Batch Processing in How to insert multiple rows into database using hibernate? Editted:我在如何使用hibernate将多行插入数据库中找到了Hibernate Batch Processing and Best way to insert a good amount of records in hibernate 在hibernate中插入大量记录的最佳方法

I am developing generic class for persist/update/delete data with hibernate, should I provide the method with 我正在使用hibernate开发持久化/更新/删除数据的泛型类,我应该提供方法

    public void (List<T> addedItemList)

or 要么

    public void (T addedItem)

For my understanding, bulk persist should be done with large amount of transactions right? 根据我的理解,批量持续应该用大量的交易完成吗? If some times there is only 1 or 2 objects to be persisted, is batch processing still appropriate? 如果有时只有1或2个对象要保留,批处理是否仍然合适?

The main point here is to begin the transaction, persist all, and then commit. 这里的要点是开始事务,持久化所有,然后提交。 Try not using the @Transaction since you are doing it with the code. 尝试不使用@Transaction,因为您正在使用代码。

                EntityManager em = entityManagerProvider.get();
//                em.clear();//remove this if caching is necessary
                em.getTransaction().begin();
                for(buildings b:buildingsArray) {
                     em.persist(b);
                }
                em.getTransaction().commit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM