1 16 17 package org.springframework.orm.hibernate; 18 19 import java.util.Collections ; 20 import java.util.HashMap ; 21 import java.util.Map ; 22 23 import net.sf.hibernate.FlushMode; 24 import net.sf.hibernate.Session; 25 import net.sf.hibernate.Transaction; 26 27 import org.springframework.transaction.support.ResourceHolderSupport; 28 import org.springframework.util.Assert; 29 30 42 public class SessionHolder extends ResourceHolderSupport { 43 44 private static final Object DEFAULT_KEY = new Object (); 45 46 50 private final Map sessionMap = Collections.synchronizedMap(new HashMap (1)); 51 52 private Transaction transaction; 53 54 private FlushMode previousFlushMode; 55 56 57 public SessionHolder(Session session) { 58 addSession(session); 59 } 60 61 public SessionHolder(Object key, Session session) { 62 addSession(key, session); 63 } 64 65 66 public Session getSession() { 67 return getSession(DEFAULT_KEY); 68 } 69 70 public Session getSession(Object key) { 71 return (Session) this.sessionMap.get(key); 72 } 73 74 public Session getValidatedSession() { 75 return getValidatedSession(DEFAULT_KEY); 76 } 77 78 public Session getValidatedSession(Object key) { 79 Session session = (Session) this.sessionMap.get(key); 80 if (session != null && !session.isOpen()) { 85 this.sessionMap.remove(key); 86 session = null; 87 } 88 return session; 89 } 90 91 public Session getAnySession() { 92 synchronized (this.sessionMap) { 93 if (!this.sessionMap.isEmpty()) { 94 return (Session) this.sessionMap.values().iterator().next(); 95 } 96 return null; 97 } 98 } 99 100 public void addSession(Session session) { 101 addSession(DEFAULT_KEY, session); 102 } 103 104 public void addSession(Object key, Session session) { 105 Assert.notNull(key, "Key must not be null"); 106 Assert.notNull(session, "Session must not be null"); 107 this.sessionMap.put(key, session); 108 } 109 110 public Session removeSession(Object key) { 111 return (Session) this.sessionMap.remove(key); 112 } 113 114 public boolean containsSession(Session session) { 115 return this.sessionMap.containsValue(session); 116 } 117 118 public boolean isEmpty() { 119 return this.sessionMap.isEmpty(); 120 } 121 122 public boolean doesNotHoldNonDefaultSession() { 123 synchronized (this.sessionMap) { 124 return this.sessionMap.isEmpty() || 125 (this.sessionMap.size() == 1 && this.sessionMap.containsKey(DEFAULT_KEY)); 126 } 127 } 128 129 130 public void setTransaction(Transaction transaction) { 131 this.transaction = transaction; 132 } 133 134 public Transaction getTransaction() { 135 return transaction; 136 } 137 138 public void setPreviousFlushMode(FlushMode previousFlushMode) { 139 this.previousFlushMode = previousFlushMode; 140 } 141 142 public FlushMode getPreviousFlushMode() { 143 return previousFlushMode; 144 } 145 146 147 public void clear() { 148 super.clear(); 149 this.transaction = null; 150 this.previousFlushMode = null; 151 } 152 153 } 154 | Popular Tags |