您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關Hibernate+JDBC實現批量插入、更新及刪除的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
具體如下:
一、批量插入(兩種方式)
1. 通過Hibernate緩存
如果這樣寫代碼進行批量插入(初始設想):
package com.anlw.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import com.anlw.entity.Student; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); for (int i = 0; i < 10; i++) { Student s = new Student(); s.setAge(i + 1); s.setName("test"); sess.save(s); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
如果數據量太大,會有可能出現內存溢出的異常;
小知識:
(1).Hibernate一級緩存,對其容量沒有限制,強制使用,由于所有的對象都被保存到這個緩存中,內存總會達到一定數目時出現內存溢出的情況;
(2).Hibernate二級緩存可以進行大小配置;
要解決內存溢出的問題,就應該定時的將Sessiion緩存中的數據刷到數據庫,正確的批量插入方式:
(1).設置批量尺寸(博主至今還沒有明白下面這個屬性和flush()方法的區別)
<property name="hibernate.jdbc.batch_size">2</property>
配置這個參數的原因就是盡量少讀數據庫,該參數值越大,讀數據庫的次數越少,速度越快;上面這個配置,是Hibernate是等到程序積累了100個sql之后在批量提交;
(2).關閉二級緩存(這個博主也不是很明白)
<property name="hibernate.cache.use_second_level_cache">false</property>
除了Session級別的一級緩存,Hibernate還有一個SessionFactory級別的二級緩存,如果啟用了二級緩存,從機制上來說,Hibernate為了維護二級緩存,在批量插入時,hibernate會將對象納入二級緩存,性能上就會有很大損失,也可能引發異常,因此最好關閉SessionFactory級別的二級緩存;
(3).在一二設置完成的基礎上,清空Session級別的一級緩存;
package com.anlw.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import com.anlw.entity.Student; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); for (int i = 0; i < 10; i++) { Student s = new Student(); s.setAge(i + 1); s.setName("test"); sess.save(s); if(i%100 == 0){ //以每100個數據作為一個處理單元 sess.flush(); //保持與數據庫數據的同步 sess.clear(); //清楚Session級別的一級緩存的全部數據,及時釋放占用的內存 } } tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
2. 繞過Hibernate,直接調用JDBC API
package com.anlw.util; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.hibernate.service.ServiceRegistry; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); //執行Work對象指定的操作,即調用Work對象的execute()方法 //Session會把當前使用的數據庫連接傳給execute()方法 sess.doWork(new Work() { @Override public void execute(Connection arg0) throws SQLException {//需要注意的是,不需要調用close()方法關閉這個連接 //通過JDBC API執行用于批量插入的sql語句 String sql = "insert into student(name,age) values(?,?)"; PreparedStatement ps = arg0.prepareStatement(sql); for(int i=0;i<10;i++){ ps.setString(1, "kobe"); ps.setInt(2,12); ps.addBatch(); } ps.executeBatch(); } }); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
注意:通過JDBC API中的PreparedStatement接口來執行sql語句,sql語句涉及到的數據不會被加載到Session的緩存中,因此不會占用內存空間,因此直接調用JDBC API批量化插入的效率要高于Hibernate緩存的批量插入;
更新&&刪除
語法格式:(HQL)
update | delete from? <ClassName> [where where_conditions]
1>在from子句中,from關鍵字是可選的,即完全可以不寫from關鍵字
2>在from子句中,只能有一個類名,可以在該類名后指定別名
3>不能在批量HQL語句中使用連接,顯示或者隱式的都不行,但可以在where子句中使用子查詢
4>整個where子句是可選的,where子句的語法sql語句中where子句的語法完全相同
5>Query.executeUpdate()方法返回一個整型值,該值是受此操作影響的記錄數量,由于hibernate的底層操作實際上是由JDBC完成的,因此,如果有批量update或delete操作被轉換成多條update或delete語句,(關聯或者繼承映射),該方法只能返回最后一條sql語句影響的記錄行數,不是所有的記錄行數,需要注意;
二、批量更新(兩種方式)
1. 使用Hibernate直接進行批量更新
(1)方式1:(Hibernate的HQL直接支持update/delete的批量更新語法)
package com.anlw.util; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); //在HQL查詢中使用update進行批量更新,下面的的語句是HQL語句,不是sql語句 Query query = sess.createQuery("update Student set name = 'www'"); query.executeUpdate(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
(2)方式2:(強烈不推薦)
package com.anlw.util; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import org.hibernate.CacheMode; import org.hibernate.Query; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.hibernate.service.ServiceRegistry; import com.anlw.entity.Student; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); //查詢表中的所有數據 ScrollableResults student = sess.createQuery("from Student") .setCacheMode(CacheMode.IGNORE) .scroll(ScrollMode.FORWARD_ONLY); int count = 0; while(student.next()){ Student s = (Student)student.get(0); s.setName("haha"); if(++count%3 == 0){ sess.flush(); sess.clear(); } } tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
通過這種方式,雖然可以執行批量更新,但效果非常不好,執行效率不高,需要先執行數據查詢,然后再執行數據更新,而且這種更新將是逐行更新,即每更新一行記錄,都要執行一條update語句,性能非常低;
2. 繞過Hibernate,調用JDBC API
(1)方式1:
package com.anlw.util; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.hibernate.service.ServiceRegistry; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); //執行Work對象指定的操作,即調用Work對象的execute()方法 //Session會把當前使用的數據庫連接傳給execute()方法 sess.doWork(new Work() { @Override public void execute(Connection arg0) throws SQLException {//需要注意的是,不需要調用close()方法關閉這個連接 String sql = "update student set name = 'oracle'"; //創建一個Satement對象 Statement st = arg0.createStatement(); //調用JDBC的update進行批量更新 st.executeUpdate(sql); } }); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
(2)方式2:
package com.anlw.util; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.hibernate.service.ServiceRegistry; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); //執行Work對象指定的操作,即調用Work對象的execute()方法 //Session會把當前使用的數據庫連接傳給execute()方法 sess.doWork(new Work() { @Override public void execute(Connection arg0) throws SQLException {//需要注意的是,不需要調用close()方法關閉這個連接 String sql = "update student set name = ? where name=?"; PreparedStatement ps = arg0.prepareStatement(sql); for(int i=0;i<10;i++){ ps.setString(1,"tom"); ps.setString(2, "oracle"); ps.addBatch(); } ps.executeBatch(); } }); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
三、批量刪除(兩種方式)
1. 使用Hibernate直接進行批量刪除
(1)方式1:(Hibernate的HQL直接支持update/delete的批量更新語法)
package com.anlw.util; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); //在HQL查詢中使用delete進行批量刪除,下面的的語句是HQL語句,不是sql Query query = sess.createQuery("delete Student");//也可以是delete from,from關鍵字是可選的,可以不要,加條件的時候可以指定類的別名 query.executeUpdate(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
(2)方式2:(強烈不推薦)
package com.anlw.util; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import org.hibernate.CacheMode; import org.hibernate.Query; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.hibernate.service.ServiceRegistry; import com.anlw.entity.Student; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); //查詢表中的所有數據 ScrollableResults student = sess.createQuery("from Student") .setCacheMode(CacheMode.IGNORE) .scroll(ScrollMode.FORWARD_ONLY); int count = 0; while(student.next()){ Student s = (Student)student.get(0); sess.delete(s); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
通過這種方式,雖然可以執行批量刪除,但效果非常不好,執行效率不高,需要先執行數據查詢,然后再執行數據刪除,而且這種刪除將是逐行刪除,即每刪除一行記錄,都要執行一條delete語句,性能非常低;
2. 繞過Hibernate,調用JDBC API
(1)方式1:
package com.anlw.util; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.hibernate.service.ServiceRegistry; import com.anlw.entity.Student; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); sess.doWork(new Work() { @Override public void execute(Connection arg0) throws SQLException { String sql = "delete from student where age > 5"; //mysql中刪除語句不能省略from Statement st = arg0.createStatement(); st.executeUpdate(sql); } }); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
2)方式2:
package com.anlw.util; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.hibernate.service.ServiceRegistry; import com.anlw.entity.Student; public class SessionUtil { Configuration conf = null; ServiceRegistry st = null; SessionFactory sf = null; Session sess = null; Transaction tx = null; public void HIbernateTest() { conf = new Configuration().configure(); st = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory(st); try { sess = sf.openSession(); tx = sess.beginTransaction(); sess.doWork(new Work() { @Override public void execute(Connection arg0) throws SQLException { String sql = "delete from student where age = ?"; //mysql中刪除語句不能省略from PreparedStatement ps = arg0.prepareStatement(sql); for(int i=0;i<10;i++){ if(i%2 == 0){ ps.setInt(1, i); ps.addBatch(); } ps.executeBatch(); } } }); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } } finally { sess.close(); sf.close(); } } public static void main(String[] args) { new SessionUtil().HIbernateTest(); } }
感謝各位的閱讀!關于“Hibernate+JDBC實現批量插入、更新及刪除”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。