Nếu insert và đẩy đồng thời cùng 1 lúc 10000 bản ghi thì sẽ xảy ra lỗi OutOfMemoryException (Lý do là hibernate sẽ lưu tất cả 10000 bản ghi vào bộ nhớ cache nhưng bộ nhớ cache không đủ)
Vậy Batch Processing là gi? Batch Processing là xử lý theo lô, tức là ta sẽ insert và đẩy từng lô bản ghi vào database.
Ví dụ ở đây ta sẽ insert và đẩy 50 bản ghi vào database cùng 1 lúc, như thế sẽ giảm số lượng connection tới database, đồng thời tránh được lỗi OutOfMemoryException
Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();for(int i=0; i<100000; i++){Customer customer =newCustomer(.....); session.save(customer);if( i %50==0){//50, same as the JDBC batch size//flush a batch of inserts and release memory: session.flush(); session.clear();}}tx.commit();session.close();
Khi bạn tạo mới đối tượng persistent, sử dụng các method flush() và clear() để điều khiển kích thương của bộ nhớ cache.
Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();for(int i=0; i<100000; i++){Customer customer =newCustomer(.....); session.save(customer);if( i %20==0){//20, same as the JDBC batch size//flush a batch of inserts and release memory: session.flush(); session.clear();}}tx.commit();session.close();
Cũng giống như lúc insert, khi truy xuất, cập nhật dữ liệu hãy dùng các method flush() và clear() để điều khiển kích thương của bộ nhớ cache. Ngoài ra sử dụng method scroll() để tận dụng các con trỏ ở server cho các truy vấn trả về nhiều hàng dữ liệu.
Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();ScrollableResults customers = session.getNamedQuery("GetCustomers").setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);int count=0;while( customers.next()){Customer customer =(Customer) customers.get(0); customer.updateStuff(...);if(++count %20==0){//flush a batch of updates and release memory: session.flush(); session.clear();}}tx.commit();session.close();