Simple Transaction control Util for simple Thread

Source: Internet
Author: User
/**
*
* @author yw04009 Bill,wu
*
*/
public class Transacitonutil {
Lacking of some try exception method, just to speeding up my developing
private static DataSource DS;
private static threadlocal<connection> ThreadLocal = new threadlocal<connection> ();
static {
try {
Properties prop = new properties ();
InputStream in = TransacitonUtil.class.getClassLoader (). getResourceAsStream ("testtransaciton.properties");
Prop.load (in);
Basedatasourcefactory factory = new Basedatasourcefactory ();//from dbcp jar
ds = Factory.createdatasource (prop);
catch (Exception e) {

}
}

public static DataSource Getdatasource () {
return DS;
}

public static Connection getconnection () {
Get the Connection for current Thread
Connection conn = Threadlocal.get ();
If there is isn't connectio on current thread, should get some one from static DataSource
if (conn = = null) {
conn = Ds.getconnection ();
Threadlocal.set (conn);
}
Return conn;
}


public static void Starttransaciton () {
Connection conn = Threadlocal.get ();
if (conn = = null) {
conn = Ds.getconnection ();
Threadlocal.set (conn);
}
Conn.setautocommit (FALSE);
}

public static void Endtransaciton () {
Connection conn = Threadlocal.get ();
IF (conn!= null) {
Conn.commit ();
}
}

public static void Closetransaciton () {
try {
Connection conn = Threadlocal.get ();
IF (conn!= null) {
Conn.close ();
}
catch (Exception e) {

finally {
Special attentions, remove connections link from currenct datacource container
Threadlocal.remove ();
}
}

}

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.