1 16 17 package org.springframework.orm.jpa.vendor; 18 19 import java.sql.Connection ; 20 import java.sql.SQLException ; 21 22 import javax.persistence.EntityManager; 23 import javax.persistence.PersistenceException; 24 25 import org.hibernate.FlushMode; 26 import org.hibernate.Session; 27 import org.hibernate.ejb.HibernateEntityManager; 28 29 import org.springframework.jdbc.datasource.ConnectionHandle; 30 import org.springframework.jdbc.datasource.SimpleConnectionHandle; 31 import org.springframework.orm.jpa.DefaultJpaDialect; 32 import org.springframework.transaction.TransactionDefinition; 33 import org.springframework.transaction.TransactionException; 34 35 43 public class HibernateJpaDialect extends DefaultJpaDialect { 44 45 public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition) 46 throws PersistenceException, SQLException , TransactionException { 47 48 super.beginTransaction(entityManager, definition); 49 Session session = getSession(entityManager); 50 FlushMode flushMode = session.getFlushMode(); 51 FlushMode previousFlushMode = null; 52 if (definition.isReadOnly()) { 53 session.setFlushMode(FlushMode.MANUAL); 55 previousFlushMode = flushMode; 56 } 57 else { 58 if (flushMode.lessThan(FlushMode.COMMIT)) { 60 session.setFlushMode(FlushMode.AUTO); 61 previousFlushMode = flushMode; 62 } 63 } 64 return new SessionTransactionData(session, previousFlushMode); 65 } 66 67 public void cleanupTransaction(Object transactionData) { 68 ((SessionTransactionData) transactionData).resetFlushMode(); 69 } 70 71 @Override 72 public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly) 73 throws PersistenceException, SQLException { 74 75 Session session = getSession(entityManager); 76 Connection con = session.connection(); 77 return (con != null ? new SimpleConnectionHandle(con) : null); 78 } 79 80 protected Session getSession(EntityManager em) { 81 return ((HibernateEntityManager) em).getSession(); 82 } 83 84 85 private static class SessionTransactionData { 86 87 private final Session session; 88 89 private final FlushMode previousFlushMode; 90 91 public SessionTransactionData(Session session, FlushMode previousFlushMode) { 92 this.session = session; 93 this.previousFlushMode = previousFlushMode; 94 } 95 96 public void resetFlushMode() { 97 if (this.previousFlushMode != null) { 98 this.session.setFlushMode(this.previousFlushMode); 99 } 100 } 101 } 102 103 } 104 | Popular Tags |