동적 프록시 접근 데이터베이스

7570 단어
테스트 -> 중개 [에이전트, 업무 코드 호출, 사무 논리 제어] -> 업무 논리 -> DAO -> 데이터베이스 구현 자바 동적 에이전트 접근 데이터베이스dome
코드 예: 데이터 액세스 계층 코드:dao 계층 코드
public interface UserDao {
/**
 *         
 * @param user
 */
void insertUser(User user);
/**
 *     
 * @param user
 */
void updateUser(User user);
}

daoImpl 레이어 코드
public class UserDaoImpl implements UserDao {

/**
 *        ,      .
 *     .    ,      .
 *         ,      /    .
 */
  @Override
  public void insertUser(User user) {
    SqlSession session = null;
    try{
        session = MyBatisUtils.openSession();
        session.insert("insertUser", user);
    }catch(Exception e){
        e.printStackTrace();
        throw e;
    }
  }

@Override
public void updateUser(User user) {
    SqlSession session = null;
      try{
        session = MyBatisUtils.openSession();
        session.update("updateUser", user);
      }catch(Exception e){
        e.printStackTrace();
        throw e;
      }
  }
}

JDBC 연결 데이터베이스 대신 Mybatis 도구 클래스 캡슐화
/**
 *       .            .
 *              .           .      .
 * 
 *   :
 *           ,  .
 *        .     .
 *  
 * java ,        ,         ,      .
 * 
 * @author Administrator
 *
 */
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
private static Map currentSessions = new HashMap<>();
/*
 *                .
 *     ,      ,           ,    .
 *           currentSessions
 *    currentSessions    .
 * ThreadLocal    ,Map       .
 *    key       ,    value         .
 *      :
 * set(T t) -> map.put(Thread.currentThread(), t);
 * get() -> map.get(Thread.currentThread());
 * remove() -> map.remove(Thread.currentThread());
 */
private static ThreadLocal localSessions = new ThreadLocal<>();
static{
    //          .
    try{
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(
                    Resources.getResourceAsStream("mybatis.cfg.xml")
                );
    }catch(Exception e){
        //          .         ?   JVM
        //              .
        throw new ExceptionInInitializerError(e);
    }
}

/*
 *         
 *     .     ,        ,            .
 *      . Thread         .
 *         ? Thread.currentThread();
 *           key,SqlSession    value,    Map  .      .
 */
public static SqlSession openSession(){
    // 1.               .
    // SqlSession session = currentSessions.get(Thread.currentThread());
    
    SqlSession session = localSessions.get();
    
    // 2.             null
    if(session == null){
        //             .
        session = sqlSessionFactory.openSession();
        // currentSessions.put(Thread.currentThread(), session);
        localSessions.set(session);
    }
    
    // 3.     
    return session;
    
    // return sqlSessionFactory.openSession();
}

/**
 *       .          ,              .          .
 */
public static void close(){
    SqlSession session = localSessions.get();
    if(session != null){
        session.close();
    }
    
    //              
    localSessions.remove();
}

}
실체류
public class User {

//    field
private Integer id;
private String name;
private String password;
  private int age;
private List address;
  @Override
public String toString() {
    return "User [id=" + id + ", name=" + name + ", password=" + password
            + ", age=" + age + "]";
}
// get/set         property  id - property
public Integer getId() {
    return id;
}
public void setId(Integer id) {
    this.id = id;
}
    public String getUsername() {
    return name;
}
public void setUsername(String name) {
    this.name = name;
}
public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
}
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
}

}

비즈니스 계층 코드 서비스
public interface UserService {
/**
 *     
 */
void register(User user);
    /**
 *     
 */
void modify(User user);
}

업무층의 실현 유형 서비스.impl
/**
 *     ,        .
 *              ,   DAO        .
 * @author Administrator
 *
 */
public class UserServiceImpl implements UserService {

private UserDao userDao ;

/**
 *     ,     .   DAO       .
 *   DAO        ,    
 *   DAO      ,    .
 */
@Override
public void register(User user) {
    System.out.println("UserServiceImpl.register  ");
    this.userDao.insertUser(user);
}

@Override
public void modify(User user) {
    this.userDao.updateUser(user);
}
}

동적 에이전트 클래스
/**
 *      .            .
 *            .
   * 
 * @author Administrator
 *
 */
public class TransactionHandler implements InvocationHandler {

private Object target;

/**
 *             .
 * @param proxy -     .            
 * @param method -      .             .  : UserServiceImpl.login();
 * @param args -        ,     ,     .
 * @return            .
 */
@Override
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
    //       
    Object returnValue = null;
    SqlSession session = null;
    //          .
    //                   .
    try{
        //       .  :     
        session = MyBatisUtils.openSession();
        System.out.println("         : " + method.getName());
        returnValue = method.invoke(target, args);
        session.commit();
    }catch(Exception e){
        e.printStackTrace();
        if(session != null)
            session.rollback();
    }finally{
        MyBatisUtils.close();
    }
    
    return returnValue;
  }

  public Object getTarget() {
    return target;
  }

  public void setTarget(Object target) {
    this.target = target;
  }
}

프록시 객체의 플랜트 클래스 작성
/**
 *            .
 *    ,         .
 *          ,         ,   UserService             .
 * 
 * @author Administrator
 *
 */
public class TransactionProxy {
//     .          .
private Object target;
private InvocationHandler h;

/**
 *       .
 *     ,        .
 *     Proxy  .
 * @return
 */
public Object getProxyInstance(){
    
    ClassLoader loader = this.getClass().getClassLoader();
    Class[] interfaces = this.target.getClass().getInterfaces();
    
    /*
     * @param loader -     .            .
     * @param interfaces -        ,       .
     * @param h -     ,        ,       .      InvocationHandler
     */
    Object proxy = Proxy.newProxyInstance(loader, interfaces, h);
    
    return proxy;
    
}

public InvocationHandler getH() {
    return h;
}

public void setH(InvocationHandler h) {
    this.h = h;
}

public Object getTarget() {
    return target;
}

public void setTarget(Object target) {
    this.target = target;
}

}

Until 테스트
 @Test
public void testDynamicProxy(){
    //
    UserService userService = new UserServiceImpl();
    ((UserServiceImpl)userService).setUserDao(new UserDaoImpl());
    //      
    TransactionProxy proxyFactory = new TransactionProxy();
    //    
    TransactionHandler h = new TransactionHandler();
    h.setTarget(userService);
    proxyFactory.setH(h);
    proxyFactory.setTarget(userService);
    UserService service = (UserService) proxy;
    //      
    User user = new User();
    user.setAge(25);
    user.setUsername("  ");
    user.setPassword("250");
    //    
    service.register(user);
}

좋은 웹페이지 즐겨찾기