仿hibernate,spring架構手動寫

來源:互聯網
上載者:User

仿hibernate,spring架構手動寫

最近學習了hibernate底層技術和spring 的底層技術,覺得很不錯,所以想分享下,要是說的不夠詳細,可以去下載資源自己查看下載連結

技術的體現是在實際中的。現在大體介紹一下吧

首先介紹hibernate手動寫:

仿HIBERNATE

hibernate是屬於DAO,專門又來管理資料的,connection中還要考慮多線程的情況,同一個線程還要必須要是相同的connection對象,這就需要ThreadLocal來實 現。

1,connection考慮需要多線程,需要採用多例模式來實現,

2,讀取設定檔,如真的hibernate中的設定檔(自己寫的只有mysqld的)

3,當需要進行事物處理的時,需要採用同一個connection對象,需要用到ThreadLocal對象進行設定

4,當connection關閉時,而不是直接關閉,只是將其還回線程池中。

具體代碼呈上:

 

 

/* * 我們需要採用線程池避免線程衝突,多例模式----》獲得時候需要上鎖 * pool中的數量是有限的,我們採用了代理模式,修改 con.close(),將串連換回來 * 為了保證統一線程是一個使用者,我們採用threadlocal本地線程技術 */public class hibernateFactory2 {private static final int NUM=3;private static List pool =new ArrayList();private static  ThreadLocal t=new ThreadLocal();//聲明本地線程、static{//讀取設定檔Properties p =new Properties();try {p.load(hibernateFactory2.class.getClassLoader().getResourceAsStream("jdbc.properties"));//讀取裡面的值,一直修改設定檔即可String driver=p.getProperty("driver");String url=p.getProperty("url");String user=p.getProperty("username");String password=p.getProperty("password");//System.out.println(driver+url+user+password);Class.forName(driver);for(int i=0;i//採用動態代理開始進行對connection介面實現代理,對con.close,實現換回去Object o =Proxy.newProxyInstance(hibernateFactory2.class.getClassLoader(), new Class[]{Connection.class},new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {if(method.getName().equals("close")){pool.add((Connection)(proxy));System.out.println("換回來了。。。");return null;}return method.invoke(con, args);}});pool.add((Connection)o);}//System.out.println("初始化完畢"+con);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static synchronized Connection getCon() throws Exception{/* * 把自動會到一個它所維護的那個map中去取,把以“當前線程對象”為key所對應的那個value取出來 */Connection c=t.get();if(c==null){while(pool.size()<=0){System.out.println("池中已經乜有串連");Thread.sleep(1000);} c=pool.remove(0);//為事物處理方便了,當出現錯誤的時候,多表一個都不能儲存。採用一個connectiont.set(c);}return c;}}

 

 

仿Spring這一層基本上進行的是商務邏輯處理 1,剛開始時候,將交易處理寫在這一層,但是對於單個的函數的,每一個需要寫,代碼太繁瑣了,所以直接將從servlet轉到service的時候(切面技術),採用代理模式代理一下,在代理模式裡面,我們採用進行事物處理,需要的我們攔截進行事物處理,不需要的,我們直接允許存取,做他自己的事情。

2,在使用代理模式的時候,為了讓外面注入不需要強轉,proxy裡面採用了泛型的引入。

具體代碼呈上:

 

public class Tx implements InvocationHandler{private Object srcobj;private Object returnValue;public Tx(Object srcobj) {this.srcobj=srcobj;}//這裡寫的是通用版本,代理模式//這個需要強轉,所以引入了下面的那個不需要強轉//public static Object getProxy(Object srcobj){//Object o =Proxy.newProxyInstance(//Tx.class.getClassLoader(), //srcobj.getClass().getInterfaces(),//new Tx(srcobj));//return o;//}/* * 下面這個是升級版本,返回的類型不用強轉 */public static T getProxy(Object srcobj){Object o =Proxy.newProxyInstance(Tx.class.getClassLoader(), srcobj.getClass().getInterfaces(),new Tx(srcobj));return (T)o;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {//所有的代理在這裡開始Connection con=null;if(method.isAnnotationPresent(MyTrans.class)){//這裡採用註解的方式來區別是都需要進行事物處理System.out.println("被攔截了");try {  con =hibernateFactory2.getCon(); con.setAutoCommit(false); returnValue=method.invoke(srcobj, args);//調用被代理的自己去執行 con.commit();System.out.println("事物提交成功");} catch (Exception e) {try {System.out.println("復原了"+e.getMessage());con.rollback();}catch (SQLException e1) {throw  new RuntimeException("復原失敗"+e.getMessage());}}finally{try {con.setAutoCommit(true);con.close();//這裡關閉,是還回池中,採用代理模式修改過}catch (SQLException e) {throw new RuntimeException("關閉資料庫連接失敗11"+e.getMessage());}}}else{System.out.println("不攔截,允許存取!!");return method.invoke(srcobj, args);}return returnValue;}}

這是自己寫的註解類

 

 

package cn.hncu.publs.tx;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)//作用於運行時,預設在編譯器@Target(value=ElementType.METHOD)//作用於方法public @interface MyTrans {}

 

歡迎各位大神指點

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.