Implementing database transactions with dynamic proxies

Source: Internet
Author: User
Tags db2 function definition rollback

Database sql:

1 CREATE TABLE T_user 2 (3    user_id              varchar (TEN) not            null, 4    user_name            varchar (+) not            null, 5
   password             varchar () not            null, 6    contact_tel          varchar ( 7 EMAIL)                VARCHAR (8),    create_date          DATE, 9    constraint p_key_1 primary KEY (user_id), insert INTO T_user (U ser_id, user_name, password) values (' Root ', ' system administrator ', ' root ');
Connectionmanager.java (Database connection management)
 1 package dynamicproxytransaction; 2 3 Import java.sql.Connection; 4 Import Java.sql.DriverManager; 5 Import java.sql.SQLException; 6 7 public class ConnectionManager {8 private ConnectionManager () {9}10 one private static threadlocal<c onnection> threadconn = new threadlocal<connection> (); 12 13//Get database connections from public static Connection Getconn                 Ection () {Connection conn = Threadconn.get (); + if (conn = = null) {# try {18}                         Class.forName ("Com.ibm.db2.jcc.DB2Driver"), conn = Drivermanager.getconnection (20                 "Jdbc:db2://127.0.0.1:50000/drp", "Db2admin", "619100"); catch (ClassNotFoundException e) {22             E.printstacktrace (); SQLException catch (E) {e.printstacktrace (); 25 }26 Threadconn.set (conn);}28 return conn;29}30 31//SET Transaction manual submission of public Stati c void BenigTransction (Connection conn) {All-try {conn! = null) {Conn.getautocommit () ) {Conn.setautocommit (false), PNS}38}39} catch (SQLException E ) {e.printstacktrace (); 41}42}43 44//COMMIT TRANSACTION public static void Endtransction (Connect                     Ion conn) {conn = null) {$ if (!conn.getautocommit ()) {49 Conn.commit ();}51}52} catch (SQLException e) {E.printstac Ktrace (); 54}55}56 57//Set the original state of the Connection the public static void Recovertransction (Connection conn) {5 9 try {$ if (conn! = null) {Conn.getautocommit ()) {conn             . Setautocommit (false); + N} else {conn.setautocommit (true); 65}66 }67}catch (SQLException e) {e.printstacktrace (); 69}70}71 72//Unexpected ROLLBACK transaction public static V             OID rollback (Connection conn) {conn! = null) {conn.rollback (); 77 }78} catch (SQLException e) {e.printstacktrace (); 80}81}82 83//Close the connection and             It deletes the public static void Close () {Connection conn = Threadconn.get () from the current thread, and if (conn! = null) {87             try {conn.close (); conn = null;90 threadconn.remove (); 91 } catch (SQLException e) {e.printstacktrace (); 93}94}95}96}

User.java (Entity Class)

 1 package dynamicproxytransaction; 2 3 Import java.util.Date;         4 5 public class User {6//User ID 7 private string ID; 8//User name 9 private string name;10 Login password each private string password;12//Contact phone number contact_tel;14//email 1  5 private string email;16//user creation date + private date create_date;18 public String getId ()         {id;21}22-public void setId (String id) {this.id = id;25 }26 public String GetName () {name;29}30 to public void SetName (String na Me) {this.name = name;33}34 public String GetPassword () {password ; PNs}38-public void SetPassword (String password) {This.password = password;41}4 2 public String Getcontact_tel () {Contact_tel return = = =Null?  "": contact_tel;45}46-public void Setcontact_tel (String contact_tel) {This.contact_tel = contact_tel;49}50 public String getemail () {return email = = NULL? "": email;53}54 public void Setemail (String email) {This.email = email;57}58 The public Date getcreate_date () {create_date;61}62 the public void setcreate _date (date create_date) {this.create_date = create_date;65}66}

Userdao.java (User-related database operations)

1 package dynamicproxytransaction;2 3 Import java.sql.sqlexception;4 5 public interface Userdao {6 public     User Seluser (String id) throws SQLException; 7}

Userdaoimpl.java (Userdao implementation Class)

 1 package dynamicproxytransaction; 2 3 Import java.sql.Connection; 4 Import java.sql.PreparedStatement; 5 Import Java.sql.ResultSet; 6 Import java.sql.SQLException; 7 8 public class Userdaoimpl implements Userdao {9 @Override10 public User seluser (String id) throws Sqlexceptio n {one ResultSet resu = null;12 String sql = "SELECT * from Db2admin. T_user WHERE user_id =? "; Connection conn = Connectionmanager.getconnection (); PreparedStatement pstat = Conn.preparestatement ( SQL), user user = Null;16 try {pstat.setstring (1, id); resu = Pstat.execute             Query (); + if (Resu.next ()) {user = GetUser (resu);}22} finally {23                 if (resu! = null) {resu.close ();}26 if (pstat! = null) {27 Pstat.close ();}29}30 return user;31}32//Get user PrivAte user GetUser (ResultSet resu) throws SQLException {User user = new user (); User.setid (ResU . getString ("user_id")), User.setname (resu.getstring ("user_name")), PNs User.setpassword (resu.getst Ring ("PASSWORD")), User.setcontact_tel (resu.getstring ("Contact_tel")), User.setemail (resu.gets         Tring ("EMAIL")), User.setcreate_date (Resu.gettimestamp ("Create_date")), return user;42 }43}

Usermanager.java (user management function definition)

1 package dynamicproxytransaction;2 3 public interface Usermanager {4 public     User Finduser (String id) throws Exceptio n; 5}

Usermanagerimpl.java (Usermanager implementation Class)

1 package dynamicproxytransaction;  2  3 import java.sql.SQLException; 4  5 public class Usermanagerimpl implements Usermanager {6     //This is not the same as I wrote before: I'm all written. In each method, the write attribute should be better, reducing the number of times the object was created 7     private Userdao Userdao = null;  8  9 Public     Usermanagerimpl () {         Userdao = new Userdaoimpl ();}12 public     User Finduser ( String ID) throws SQLException {         return userdao.seluser (ID);     }16}

Transactionproxy.java (Proxy implementation)

 1 package dynamicproxytransaction; 2 3 Import Java.lang.reflect.InvocationHandler; 4 Import java.lang.reflect.InvocationTargetException; 5 Import Java.lang.reflect.Method; 6 Import Java.lang.reflect.Proxy; 7 Import java.sql.Connection; 8 9 public class Transactionproxy implements Invocationhandler {Ten private Object obj = null;11//obj: class requiring proxy 1 3 public Object Newproxyinstance (object obj) {this.obj = obj;15 return Proxy.newproxyinstance (this. Obj.getclass (). getClassLoader (), This.obj.getClass (). Getinterfaces (), this);}18 @Override2 0 public Object Invoke (object proxy, Method method, object[] args) throws Throwable {22///for receiving parameters                 Number of objects param = null;24//If it is the beginning of the following method, then the agent transaction is (Method.getname (). StartsWith ("add") 26 || Method.getname (). StartsWith ("modify") 27 | | Method.getname (). StartsWith ("find") 28 | | Method.getname (). StartswitH ("Del")) {Connection conn = connectionmanager.getconnection (); try {31//Manual                 Submit Transaction connectionmanager.benigtransction (conn); param = Method.invoke (obj, args); 34                 COMMIT TRANSACTION (conn); Connectionmanager.endtransction catch (Exception e) {37 ROLLBACK TRANSACTION Connectionmanager.rollback (conn); (e instanceof Invocationtarget Exception) {InvocationTargetException INV = (invocationtargetexception) e;41st Row inv.gettargetexception (); Exception} else {The "operation failed!"); }45} finally {46//restore Status CONNECTIONMANAGER.RECOVERTRANSC tion (conn); Connectionmanager.close ();}50}51 return param;52}53}

Test.java (Test)

1 package dynamicproxytransaction; 2  3 public class Test {4 public     static void Main (string[] args) throws Exception {5         transactionproxy TRANSCT Ionproxy = new Transactionproxy (); 6  7////         Generate proxy Object 8         Usermanager Usermanager = (usermanager) Transctionproxy 9                 . Newproxyinstance (New Usermanagerimpl ()); user         user = Usermanager.finduser ("root"),         System.out.println ("username:" + user.getname ());     }13     14}

Implementing database transactions with dynamic proxies

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.