QueryRunner,结果集的详细,ThreadLocal控制事物和AOP编程

QueryRunner的基本练习:
public class DBUtilDemo {
 private QueryRunner qr=new QueryRunner(DBCPUtil.getDataSource());
 @Test
 public void testAdd() throws SQLException{
  qr.update("insert into account(name,money) values(?,?)", "fff",1000);
 }
 @Test
 public void testFindOne() throws SQLException{
  Account a=qr.query("select *from account where id=?", new BeanHandler<Account>(Account.class),1);
  System.out.println(a);
 }
 @Test
 public void testFindAll() throws SQLException{
  qr.query("select *from account", new BeanListHandler<Account>(Account.class));
 }
 @Test
 //批处理
 public void testBath() throws SQLException{
  Object params[] []=new Object[10][];
  for(int i=0;i<params.length;i++){
   params[i]=new Object[]{i+1,i+1};
  }
  qr.batch("insert into account(name,money) values(?,?)",params);
 }
}

结果集的详细:
public class ResultSetHandlerDemo {
 private QueryRunner qr=new QueryRunner(DBCPUtil.getDataSource());
 @Test
 //ArrayHandler 将获取到的第一个结果集封装到一个数组中
 public void test1() throws SQLException{
  Object objs[]=qr.query("selcet *from account where id=?",new ArrayHandler() , 1);
  for(Object obj:objs){
   System.out.println(obj);
  }
 }
 //把结果集中的每一行数据封装到数据中
 public void test2() throws SQLException{
  List<Object[]> list=qr.query("selcet *from account",new ArrayListHandler());
  for(Object[] objs:list){
   for(Object obj:objs){
    System.err.println(obj);
   }
  }
 }
 //将某一列数据封装到数据
 public void test3() throws SQLException{
  List<Object> list=qr.query("selcet *from account",new ColumnListHandler("name"));
  for(Object objs:list){
   System.err.println(objs);
  }
 }
 //KeyedHandler,将获取到的数据封装到map中
 public void test4() throws SQLException{
  Map<Object, Map<String, Object>> bmap=qr.query("selcet *from account",new KeyedHandler("id"));
  for(Map.Entry<Object, Map<String, Object>> maps:bmap.entrySet()){
   for(Map.Entry<String, Object> map:maps.getValue().entrySet()){
    System.out.println(map.getKey()+map.getValue());
   }
  }
 }
 //将获取到的第一行数据封装到map中
 public void test5() throws SQLException{
  Map<String, Object> map=qr.query("selcet *from account where id=?",new MapHandler(),1);
  for(Map.Entry<String, Object> lme:map.entrySet()){
   System.out.println(lme.getKey()+lme.getValue());
  }
 }
 //将数据封装到map里,再放到list中
 public void test6() throws SQLException{
  List<Map<String, Object>> list=qr.query("selcet *from account",new MapListHandler());
  for(Map<String, Object> lme:list){
   for(Map.Entry<String, Object> map:lme.entrySet()){
    System.out.println(map.getKey()+map.getValue());
   }
  }
 }
 //只有一条记录的投影查询(就显示列的数据)
 public void test7() throws SQLException{
  Object obj=qr.query("selcet count(*) from account",new ScalarHandler(1));
  System.out.println(obj);
 }
}

 

ThreadLocal控制事物和AOP编程:
代码体现:
1TransactionManager工具类:
public class TransactionManager {
  private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
  
  public static Connection getConnection(){
   try {
    Connection conn = tl.get();//从当前线程上获取链接
    if(conn==null){
     conn = DBCPUtil.getDataSource().getConnection();//没有就从池中取一个
     tl.set(conn);//绑定到当前线程上
    }
    return conn;
   } catch (SQLException e) {
    throw new RuntimeException("从数据源获取链接失败");
   }
  }
  public static void startTransaction(){
   Connection conn = getConnection();
   try {
    conn.setAutoCommit(false);
   } catch (SQLException e) {
    throw new RuntimeException(e);
   }//开始事务
  }
  public static void commit(){
   Connection conn = getConnection();
   try {
    conn.commit();
   } catch (SQLException e) {
    throw new RuntimeException(e);
   }
  }
  public static void rollback(){
   Connection conn = getConnection();
   try {
    conn.rollback();
   } catch (SQLException e) {
    throw new RuntimeException(e);
   }
  }
  public static void release(){
   Connection conn = getConnection();
   try {
    conn.close();
    tl.remove();//从当前线程上解绑。(服务器用到了线程池的技术)
   } catch (SQLException e) {
    throw new RuntimeException(e);
   }
  }
}

2配置文件:
object.properties
accountDao=/day_20/src/cn/itcast/dao/impl/AccountDaoImpl.java
businessService=/day_20/src/cn/itcast/businessService/impl/AccountBusinessServiceImpl.java

3BeanFactory
public class BeanFactory {
 //返回BusinessService的实现类的代理对象
 
  //面向切面编程:AOP
  public static BusinessService getBusinessServiceImpl(){
   final BusinessService s = new BusinessServiceImpl();
   BusinessService proxyS = (BusinessService)Proxy.newProxyInstance(s.getClass().getClassLoader(),
     s.getClass().getInterfaces(), new InvocationHandler() {
      public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
       try{
        TransactionManager.startTransaction();//开始事务
        Object rtValue = method.invoke(s, args);
        TransactionManager.commit();
        return rtValue;
       }catch(Exception e){
        TransactionManager.rollback();
        throw new RuntimeException(e);
       }finally{
        TransactionManager.release();
       }
       
      }
     });
   return proxyS;
  }
}

4业务实现类:
public class BusinessServiceImpl implements BusinessService {
 private AccountDaoImpl dao = new AccountDaoImpl();
 public void transfer(String sourceAccountName, String targAccountName,float money) {
   Account sAccount=dao.findAccountByName(sourceAccountName);
   Account tAccount=dao.findAccountByName(targAccountName);
   
   sAccount.setMoney(sAccount.getMoney()-money);
   tAccount.setMoney(tAccount.getMoney()+money);
   dao.updateAccount(tAccount);
   dao.updateAccount(sAccount);
   TransactionManager.commit(); 
 }
}

转载于:https://my.oschina.net/u/1589656/blog/290519

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值