2015/5/19

about ThreadLocal......


From:
http://minglight.pixnet.net/blog/post/35569918-threadlocal
http://blog.csdn.net/qjyong/article/details/2158097

直接講感言:
threadLocal提供了一個比較安全的方式,利用currentThread為PKey,
來取得當前thread的區域變數
我自己也實做類似的方式,但是沒有threadLocal來的安全
建立一個大家都要繼承的Object,裡面宣告一個static的Map
 然後利用Thread.currentThread().getName()+"Name",來存放當時的TX與session

public abstract class ServerObject {
   protected final static HashMap<String,Thread> threadPoolHashMap=new HashMap<String, Thread>();
   protected final static HashMap<String,Object> threadPoolSessionObjectHashMap=new HashMap<String, Object>();
   protected Transaction tx;
   protected org.hibernate.Session Hibernatesession;
     protected void reloadProperty() throws FileNotFoundException, IOException {
        Hibernatesession=(Session) threadPoolSessionObjectHashMap.get(Thread.currentThread().getName()+"hibernate-session");
        tx= (Transaction) threadPoolSessionObjectHashMap.get(Thread.currentThread().getName()+"hibernate-transaction");
      }
   
}

一開始進入點,就先宣告好當時的session,並且宣告好開始TX
Hibernatesession = HibernateSessionFactory.getSession();
threadPoolSessionObjectHashMap.put(Thread.currentThread().getName()+"hibernate-session", Hibernatesession);
tx = Hibernatesession.beginTransaction();
threadPoolSessionObjectHashMap.put(Thread.currentThread().getName()+"hibernate-transaction", tx);

之後一層一層繼承下來,需要取用的時候才抓出來

這樣看起來好處是:自己開發的,自己習慣
壞處就是:其他object要取值、remove,無法控制

後續再來找時間研究 有沒有更幽雅寫法

沒有留言:

JPA+complex key+custom Query

  來源: https://www.cnblogs.com/520playboy/p/6512592.html   整個來說,就是有複合主鍵 然後要使用  public interface XxXXxx DAO extends CrudRepository<Tc...