Similar to hibernate and manually written by spring framework

Source: Internet
Author: User

Similar to hibernate and manually written by spring framework

I recently learned the underlying technology of hibernate and spring, and I think it is very good. So I 'd like to share it with you. If you are not talking about it in detail, you can download the resources and view the download link.

Technology is embodied in reality. Let's give a general introduction.

First, we will introduce manual hibernate writing:

Similar to HIBERNATE

Hibernate is a type of DAO, which is used to manage data. It also needs to consider multithreading in connection. The same thread must have the same connection object, which requires ThreadLocal to implement.

1. multi-threading is required for connection consideration, and multi-sample mode is required,

2. Read the configuration file, such as the configuration file in hibernate (only mysqld is written by myself)

3. When transaction processing is required, the same connection object must be used and ThreadLocal object must be used for setting.

4. When the connection is closed, instead of directly closed, it is only returned to the thread pool.

The specific code is presented as follows:

 

 

/** We need to use the thread pool to avoid thread conflicts. In the multi-sample mode, the number of locks in the pool is limited. We use the proxy mode to modify con. close (), change the connection back * to ensure that the unified thread is a user, we use threadlocal local Thread Technology */public class hibernateFactory2 {private static final int NUM = 3; private static List
 
  
Pool = new ArrayList
  
   
();
  
 Private static ThreadLocal  T = new ThreadLocal  (); // Declare the local thread,  Static {// Read the configuration fileProperties p = new Properties (); try {p. load (hibernateFactory2.class. getClassLoader (). getResourceAsStream ("jdbc. properties "); // read the value in the file and modify the configuration file until 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
 
  // Use dynamic proxy to implement proxy for the connection interface, and switch back to con. closeObject 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 ("returns... "); Return null;} return method. invoke (con, args) ;}}); pool. add (Connection) o);} // System. out. println ("initialization completed" + 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 {/**
  It is automatically retrieved from a map maintained by it, and the value corresponding to the "current thread object" as the key is obtained.*/Connection c = t. get (); if (c = null) {while (pool. size () <= 0) {System. out. println ("A connection has been established in the pool"); Thread. sleep (1000);} c = pool. remove (0); // This is convenient for transaction processing. When an error occurs, multiple tables cannot be stored. Use a connectiont. set (c);} return c ;}}
 

 

 

Similar to Spring, this layer basically performs business logic processing 1. At the beginning, the transaction processing is written in this layer. However, for a single function, each layer needs to be written, the code is too cumbersome, so when you directly switch from servlet to service ( Aspect Technology), Proxy mode is used for proxy. In proxy mode, we use transaction processing. We need to intercept the transaction for processing. If this is not necessary, we can directly release it, do his own thing.

2. When using the proxy mode, in order to make the external injection do not require strong conversion, the proxy adopts the generic introduction.

The specific code is presented as follows:

 

Public class Tx implements InvocationHandler {private Object srcobj; private Object returnValue; public Tx (Object srcobj) {this. srcobj = srcobj ;}// The general version and proxy mode are written here.// This requires strong conversion, so the following one does not require strong conversion // public static Object getProxy (Object srcobj) {// Object o = Proxy. newProxyInstance (// Tx. class. getClassLoader (), // srcobj. getClass (). getInterfaces (), // new Tx (srcobj); // return o ;//}/**The following is an upgraded version. The returned type does not need to be converted.*/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 {// All proxies start Connection con = null here;
  If (method. isAnnotationPresent (MyTrans. class) {// The annotation method is used here. The difference is that transaction processing is required.System. out. println ("intercepted"); try {con = hibernateFactory2.getCon (); con. setAutoCommit (false); returnValue = method. invoke (srcobj, args); // call the proxy to execute con. commit (); System. out. println ("transaction submitted successfully");} catch (Exception e) {try {System. out. println ("rolled back" + e. getMessage (); con. rollback ();} catch (SQLException e1) {throw new RuntimeException ("rollback failed" + e. getMessage () ;}} finally {try {con. setAutoCommit (true); con. close ();// Close here. It is returned to the pool and modified in proxy mode} catch (SQLException e) {throw new RuntimeException ("failed to close database connection 11" + e. getMessage () ;}} else {System. out. println ("no interception, allow !! "); Return method. invoke (srcobj, args);} return returnValue ;}}
 

This is a self-written annotation class.

 

 

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) // At RUNTIME, the default value is @ Target (value = ElementType. METHOD) // Act on the public @ interface MyTrans {}

 

Thank you for your advice.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.