The student information for this example adds transactions to the database (you can commit the transaction, rollback the transaction, and use local thread refinement)
Main Page index.jsp
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ taglib "uri=" http://java.sun.com/jsp
/jstl/core "prefix=" C "%>
Tool Kits
Get tools for database connections Connutils5.java
Package cn.hncu.utils;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.util.ArrayList;
Import java.util.List;
Import java.util.Properties; public class ConnUtils5 {//local thread management object, for implementation: the connection obtained by the same thread is the same private static threadlocal< connection> t=new Threadloc
Al<connection> ();
Private final static list<connection> pool=new arraylist<connection> ();
private static int size;//is read by the resource file private ConnUtils5 () {} static{Properties P=new properties (); try {//The following method can read a resource file under Classpath in a pure Java project, but cannot read the Java EE project.
Because Tomcat changed the system's default class loader to//p.load (Classloader.getsystemclassloader (). Getsystemresourceasstream ("jdbc.properties"));
P.load (Classloader.getsystemresourceasstream ("jdbc.properties")); Read the resource file under the classpath of the Web project, which can be P.load (ConnUtils3.class.getClassLoader (). getResourceAsStream ("Jdbc.properties")
); String driver=p.GetProperty ("Driver");
String url=p.getproperty ("url");
String Name=p.getproperty ("username");
String pwd=p.getproperty ("password");
String ssize=p.getproperty ("size");
Size=integer.parseint (ssize);
Class.forName (driver);
for (int i=0;i<size;i++) {final Connection con=drivermanager.getconnection (URL,NAME,PWD);
System.out.println ("con==" +con); Change the Conn.close () method//Use proxy mode to generate an enhanced version of the Conn object, and its close () method to intercept the object Ncon=proxy.newproxyinstance (connutils3.cl
Ass.getclassloader (),//Conn.getclass (). Getinterfaces (),//After this method is not possible, should be the implementation class in the drive and our current program is not in the same space (ClassLoader different) New Class[]{connection.class}, new Invocationhandler () {@Override public object Invoke (object proxy, Method method, object[] args throws Throwable {if (Method.getname (). Equals ("Close")) {SYSTEM.O
Ut.println ("Return a Link:" + (Connection) proxy);
Pool.add ((Connection) proxy);
return null; Return method. Invoke (con, args);
}
});
Pool.add ((Connection) ncon);
} catch (Exception e) {e.printstacktrace (); } public static synchronized Connection getconnection () {//Take it first from T, if any, take it out if it is not in the pool and put the object in T Connection con=t.get ()
;
if (con==null) {if (Pool.size () <=0) {System.out.println ("The pool is disconnected ...");
try {thread.sleep (1000);
catch (Interruptedexception e) {e.printstacktrace ();
return getconnection ();
} con=pool.remove (0);
T.set (con);//Put into T} return con;//take one Move one}}
Agent
Package cn.hncu.utils;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
Import java.sql.Connection;
Import java.sql.SQLException;
public class Txproxy implements Invocationhandler {private Object srcobj=null;
Private Txproxy (Object srcobj) {this.srcobj = Srcobj;
public static object GetProxy (object srcobj) {System.out.println ("Srcobj:" +srcobj); Object newobj=proxy.newproxyinstance (TxProxy.class.getClassLoader (), Srcobj.getclass (). Getinterfaces (), New
Txproxy (srcobj));
System.out.println ("NEWOBJ:" +newobj);
return NEWOBJ; @Override public Object Invoke (Object Proxy, Method method, object[] args) throws Throwable {Connection Con=nul
L
Object Returnobj=null;
try {con=connutils5.getconnection ();
System.out.println ("Invoke Get a Link:" +con);
Con.setautocommit (FALSE);
Returnobj=method.invoke (srcobj, args);
System.out.println ("Submit a transaction ...");
Con.commit (); Catch(Exception e)
{try {System.out.println ("Roll back a transaction ...");
Con.rollback ();
catch (SQLException E1) {e1.printstacktrace ();
}finally{try {con.setautocommit (true);
Con.close ();
catch (SQLException e) {e.printstacktrace ();
} return returnobj;
}
}
Agent 2: no need for a strong turn, but agent all
Package cn.hncu.utils;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
Import java.sql.Connection;
Import java.sql.SQLException;
public class TxProxy2 implements Invocationhandler {private Object srcobj=null;
Private TxProxy2 (Object srcobj) {this.srcobj = Srcobj;
Public static<t> T GetProxy (class<t> c) {Object obj=null;
try {obj = c.newinstance ();
catch (Exception e) {e.printstacktrace (); Object newobj=proxy.newproxyinstance (TxProxy2.class.getClassLoader (), C.getinterfaces (), New TxProxy2 (o
BJ));
Return (T) newObj; @Override public Object Invoke (Object Proxy, Method method, object[] args) throws Throwable {Connection Con=nul
L
Object Returnobj=null;
try {con=connutils5.getconnection ();
System.out.println ("Invoke Get a Link:" +con);
Con.setautocommit (FALSE);
Returnobj=method.invoke (srcobj, args);
System.out.println ("Submit a transaction ..."); COn.commit ();
catch (Exception e) {try {System.out.println ("Roll back a transaction ...");
Con.rollback ();
catch (SQLException E1) {e1.printstacktrace ();
}finally{try {con.setautocommit (true);
Con.close ();
catch (SQLException e) {e.printstacktrace ();
} return returnobj;
}
}
Annotations
Package cn.hncu.utils;
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;
@Target (Value=elementtype.method)
@Retention (retentionpolicy.runtime) public
@interface Transaction {
}
Agent 3: use annotations to achieve transactions with transactions
Package cn.hncu.utils;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
Import java.sql.Connection;
Import java.sql.SQLException;
public class TxProxy3 implements Invocationhandler {private Object srcobj=null;
Private TxProxy3 (Object srcobj) {this.srcobj = Srcobj; Public static<t> t GetProxy (t srcobj) {Object newobj=proxy.newproxyinstance (TxProxy3.class.getClassLoade
R (), Srcobj.getclass (). Getinterfaces (), New TxProxy3 (Srcobj));
Return (T) newObj;
@Override public Object Invoke (object proxy, methods method, object[] args) throws Throwable {*/* to implement blocking only the specified method if (Method.getname (). Equals ("Close")) {...
Intercept}else{return Method.invoke (srcobj, args);
} */if (method.isannotationpresent (Transaction.class)) {Connection con=null;
Object Returnobj=null;
try {con=connutils5.getconnection ();
System.out.println ("Invoke Get a Link:" +con); Con.setautocommit (fAlse);
Real business code, release Returnobj=method.invoke (Srcobj, args);
System.out.println ("Submit a transaction ...");
Con.commit ();
catch (Exception e) {try {System.out.println ("Roll back a transaction ...");
Con.rollback ();
catch (SQLException E1) {e1.printstacktrace ();
}finally{try {con.setautocommit (true);
Con.close ();
catch (SQLException e) {e.printstacktrace ();
} return returnobj;
}else{System.out.println ("No business annotations, direct release!");
Return Method.invoke (srcobj, args);
}
}
}
Resource File Jdbc.properties
# #MySQL
driver=com.mysql.jdbc.driver
url=jdbc:mysql://127.0.0.1:3306/hncu?useunicode=true& Characterencoding=utf-8
username=root
password=1234
size=3
# #Oracle
#driver = Oracle.jdbc.driver.OracleDriver
#url =jdbc:oracle:thin:@127.0.0.1:1521:orcl
#username =scott
# Password=tiger
Stud layer of the servlet layer –queryservlet.java
Package cn.hncu.stud.servlet;
Import java.io.IOException;
Import java.util.List;
Import Java.util.Map;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Cn.hncu.domain.Book;
Import Cn.hncu.domain.Stud;
Import Cn.hncu.stud.service.IStudService;
Import Cn.hncu.stud.service.StudServiceImpl;
Import Cn.hncu.utils.TxProxy3; public class Queryservlet extends HttpServlet {//injection//1.//Istudservice service= (Istudservice) txproxy.getproxy (New S
Tudserviceimpl ());
2.
Istudservice Service=txproxy2.getproxy (Studserviceimpl.class);
3.
Istudservice Service=txproxy3.getproxy (New Studserviceimpl ()); public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {D
Opost (request, response); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexception {String cmd=request.getparameter ("cmd");
System.out.println ("cmd:" +cmd);
if ("Query". Equals (cmd)) {Query (request, response);
}else if ("Add". Equals (cmd)) {Add (request, response); } public void query (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexceptio
n {System.out.println ("service:" +service);
List<map<string, string>> studs=service.query ();
Request.setattribute ("studs", studs);
Request.getrequestdispatcher ("/jsps/show.jsp"). Forward (request, response); } public void Add (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {/
/1 Collect parameter 2 organization parameters (ID fields to be filled in DAO) String name[]=request.getparametervalues ("name");
Stud s=new Stud ();
S.setname (Name[0]);
Library information String books[]=request.getparametervalues ("book"); Protection---Price protection should also be written, here we are lazy if (books==null| |
books.length<=0) {return;
} String prices[]=request.getparametervalues ("price"); For (int i=0;i<books.length;i++) {Book b=new book ();
B.setname (Books[i]);
B.setprice (Double.parsedouble (prices[i));
※ completes the "one-to-many" relationship of two value objects Data Encapsulation S.getbooks (). Add (b);//One b.sets (s);//Multiparty}//3 invokes service layer try {service.save (s);
catch (Exception e) {//Guide failed Page}}}
The service layer of the stud layer –
Interface:
Package cn.hncu.stud.service;
Import java.util.List;
Import Java.util.Map;
Import Cn.hncu.domain.Stud;
Import cn.hncu.utils.Transaction;
Public interface Istudservice {public
list<map<string, string>> query ();
Note that annotations are only placed on an interface,,,, the method written in the implementation class is invalid (does not decide to open the transaction)
@Transaction public
void Save (Stud Stud) throws Exception;
}
Implementation class
package cn.hncu.stud.service;
Import java.sql.Connection;
Import java.sql.SQLException;
Import java.util.List;
Import Java.util.Map;
Import Cn.hncu.domain.Stud;
Import Cn.hncu.stud.dao.BookDAO;
Import Cn.hncu.stud.dao.BookJdbcDao;
Import Cn.hncu.stud.dao.StudDAO;
Import Cn.hncu.stud.dao.StudJdbcDAO;
Import CN.HNCU.UTILS.CONNUTILS5;
* * We will usually use a DAO standalone operation in the future development of a table, there are several entity tables in the system to write a few DAO, * after the framework is so dry, we have to do so, because the structure is good!
* * In the case of transactions: * 1, if there is only one DAO, but to execute multiple SQL statements and involve additions and deletions, then open transaction * 2, if a service calls multiple DAO, usually also open transaction.
* * Public class Studserviceimpl implements Istudservice {//injection Studdao dao_stud=new Studjdbcdao ();
Bookdao dao_book=new Bookjdbcdao ();
@Override public list<map<string, string>> query () {return dao_stud.query ();
@Override public void Save (Stud Stud) throws Exception {Dao_stud.save (Stud);
Dao_book.save (Stud.getbooks ()); }
}
The DAO layer of the Stud layer –
Stud Interface – separation procedure, a table corresponding to a DAO, preparing for the framework
Package Cn.hncu.stud.dao;
Import java.util.List;
Import Java.util.Map;
Import Cn.hncu.domain.Stud;
Public interface Studdao {public
list<map<string, string>> query ();
public void Save (Stud Stud) throws Exception;
}
Stud Implementation Class
Package Cn.hncu.stud.dao;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Java.util.UUID;
Import Cn.hncu.domain.Book;
Import Cn.hncu.domain.Stud;
Import CN.HNCU.UTILS.CONNUTILS3; public class Studjdbcdao implements Studdao {@Override public list<map<string, string>> query () {LIST&L T
Map<string, string>> list=new arraylist<map<string,string>> ();
A Map is a row of data, list<map> is the entire data table Connection Con=null;
try {con=connutils3.getconnection ();
Statement st=con.createstatement ();
String sql= "SELECT * from Stud";
ResultSet rs=st.executequery (SQL);
while (Rs.next ()) {map<string,string> m=new hashmap<string, string> ();
M.put ("id", (String) Rs.getobject (1));
M.put ("Name", (String) Rs.getobject (2)); List. Add (m);
} rs.close ();
St.close ();
catch (SQLException e) {e.printstacktrace ();
}finally{try {con.close ();
catch (SQLException e) {e.printstacktrace ();
} return list;
@Override public void Save (Stud Stud) throws Exception {Connection con=connutils3.getconnection ();
System.out.println ("Get a Link:" +con);
String sql= "INSERT into stud values (?,?)";
String Uuid=uuid.randomuuid (). toString (). Replace ("-", "");
PreparedStatement pst=con.preparestatement (SQL);
Stud.setid (UUID)//for "multi-party" that book can get "one side" of the ID, specialized complement pst.setstring (1, UUID);
Pst.setstring (2, Stud.getname ());
System.out.println ("1:" +uuid+ ", 2:" +stud.getname ());
Pst.executeupdate ();
Con.close ()//Get the same con, there's no need to turn it off}}
Book Interface
Package Cn.hncu.stud.dao;
Import java.util.List;
Import Cn.hncu.domain.Book;
Public interface Bookdao {public
void Save (List<book> books) throws Exception;
}
Book Implementation class
Package Cn.hncu.stud.dao;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import java.util.List;
Import Cn.hncu.domain.Book;
Import CN.HNCU.UTILS.CONNUTILS3;
public class Bookjdbcdao implements Bookdao {
@Override public
void Save (List<book> books) throws Exception {
Connection con=connutils3.getconnection ();
System.out.println ("Get a Link:" +con);
String sql= "INSERT INTO book (Name,price,studid) VALUES (?,?,?)";
PreparedStatement pst=con.preparestatement (SQL);
for (book b:books) {
pst.setstring (1, B.getname ());
Pst.setdouble (2, B.getprice ());
Pst.setobject (3, "12132312");//exception (intentionally to a nonexistent foreign key field to test transaction rollback)--Measure transaction rollback
// Pst.setobject (3, B.gets (). GetId ());
System.out.println ("1:" +b.getname () + ", 2:" +b.getprice () + ", 3:" +b.gets (). GetId ());
Pst.addbatch (),//Add to Batch
}
Pst.executebatch ()//Execute batch
// con.close (); I got the same con here, there's no need to shut it down.
}
}
Value Object
Stud objects
Package cn.hncu.domain;
Import java.util.ArrayList;
Import java.util.List;
* * * a One-to-many "one" side value object of the building method
* * Public
class Stud {
private String ID;
private String name;
※ specifically for "many" side to add a set---embodies the "one-to-many relationship" in multiple tables
private list<book> books=new arraylist<book> ();/Note that The collection is to be new when it is constructed or before. Public
String GetId () {return
ID;
}
public void SetId (String id) {
this.id = ID;
}
Public String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
Public list<book> Getbooks () {return books
;
}
public void Setbooks (List<book> books) {
this.books = books;
}
@Override public
String toString () {return
' id= + ID + ', ' + name + ', ' + books;
}
}
Book Object
Package cn.hncu.domain;
* * * the "multi" square value object of the construction method * * Public
class Book {
private Integer ID;
The base data types are all declared with the wrapper class, ready to use the framework for later---wrapper classes can be compatible with the framework (because the generic framework uses class reflection)
private String name;
Private Double Price;
※ for "One" side to add a variable of the object type (note, do not studid)---embodies the "one-to-many relationship" in multiple tables
private Stud s;//set owner
//private String studid;// ★ Don't do this
. Set public Integer getId () {return
ID;
}
public void SetId (Integer id) {
this.id = ID;
}
Public String GetName () {return
name;
}
public void SetName (String name) {
this.name = name;
}
Public Double GetPrice () {return price
;
}
public void Setprice (Double price) {
This.price = Price;
}
Public Stud GetS () {return
s;
}
public void SetS (Stud s) {
THIS.S = s;
}
* * * Multiple Table association when the ToString () method to pay attention to a trap, is one side of the output of the other side, while the other side and in turn output the previous side, the formation of infinite recursion!
* *
@Override public
String toString () {return
"id= + ID +", "+ Name +", "+ price;//cannot output stud object here, no Then infinite recursion
}
}
Show Student Information page jsps/show.jsp
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ taglib
"uri=" http:// Java.sun.com/jsp/jstl/core "prefix=" C "%>
Effect Chart:
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.