블로그 이미지

calendar

1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
  • total
  • today
  • yesterday
2023. 3. 21. 09:50 JAVA오픈소스/Spring
posted by 천상의날개
2022. 8. 23. 14:59 JAVA오픈소스/Spring

  ApplicationContextProvider  
  

  1.   @Component  
  2. public class ApplicationContextProvider implements ApplicationContextAware {  
  3.       
  4.     private static ApplicationContext ctx;  
  5.       
  6.     @Override  
  7.     public void setApplicationContext(ApplicationContext ctx) throws BeansException {  
  8.         this.ctx = ctx;  
  9.     }  
  10.       
  11.     public static ApplicationContext getApplicationContext() {  
  12.         return ctx;  
  13.     }  
  14. }  

  사용법  
  

  1. ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();  
  2. Test test = (Test)ctx.getBean(Test.class);  

posted by 천상의날개
2022. 7. 19. 16:33 JAVA오픈소스/Spring

(String) request.getAttribute("javax.servlet.forward.request_uri")

posted by 천상의날개
2020. 7. 13. 16:34 JAVA오픈소스/Spring

HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

 

http://dveamer.github.io/backend/SpringRequestContextHolder.html

posted by 천상의날개
2020. 5. 28. 16:24 JAVA오픈소스/Spring

로깅할 문자의 {}에 차례대로 값이 들어감

logger.info("test:{} test1:{}","testlg","testlg1")

결과 : test : testlg test1:testlg1

posted by 천상의날개
2020. 1. 17. 17:59 JAVA오픈소스
posted by 천상의날개
2016. 12. 20. 15:34 JAVA오픈소스/Spring

public String test(HttpServletRequest request, Model model, @RequestParam MultiValueMap<String, Object> multiParams){

List<Object> ischks = multiParams.get("ischk");
for(int i=0; i < ischks.size() ; i++){

String testCd = multiParams.get("test_cd").get(i);

}

}

posted by 천상의날개
2016. 3. 25. 17:30 JAVA오픈소스/mybatis
플러그인 소스
  1. import java.sql.Statement;  
  2. import java.util.List;  
  3. import java.util.Map;  
  4. import java.util.Properties;  
  5.   
  6. import org.apache.ibatis.executor.statement.StatementHandler;  
  7. import org.apache.ibatis.mapping.BoundSql;  
  8. import org.apache.ibatis.mapping.ParameterMapping;  
  9. import org.apache.ibatis.plugin.Interceptor;  
  10. import org.apache.ibatis.plugin.Intercepts;  
  11. import org.apache.ibatis.plugin.Invocation;  
  12. import org.apache.ibatis.plugin.Plugin;  
  13. import org.apache.ibatis.plugin.Signature;  
  14. import org.apache.ibatis.session.ResultHandler;  
  15. import org.slf4j.Logger;  
  16. import org.slf4j.LoggerFactory;  
  17.   
  18. @Intercepts({  
  19.     @Signature(type=StatementHandler.class, method="update", args={Statement.class})  
  20.     , @Signature(type=StatementHandler.class, method="query", args={Statement.class, ResultHandler.class})  
  21. })  
  22. public class LoggingPlugin implements Interceptor {  
  23.   
  24.     private Logger logger = LoggerFactory.getLogger(this.getClass());  
  25.       
  26.     @Override  
  27.     public Object intercept(Invocation invocation) throws Throwable {  
  28.     // TODO Auto-generated method stub  
  29.         StatementHandler handler = (StatementHandler)invocation.getTarget();  
  30.           
  31.         BoundSql boundSql = handler.getBoundSql();  
  32.           
  33.         // 쿼리문을 가져온다(이 상태에서의 쿼리는 값이 들어갈 부분에 ?가 있다)  
  34.         String sql = boundSql.getSql();  
  35.           
  36.           
  37.         // 쿼리실행시 맵핑되는 파라미터를 구한다  
  38.         Object param = handler.getParameterHandler().getParameterObject();  
  39.           
  40.         if(param == null){              // 파라미터가 아무것도 없을 경우  
  41.             sql = sql.replaceFirst("\\?""''");  
  42.         }else{                      // 해당 파라미터의 클래스가 Integer, Long, Float, Double 클래스일 경우  
  43.             if(param instanceof Integer || param instanceof Long || param instanceof Float || param instanceof Double){  
  44.             sql = sql.replaceFirst("\\?", param.toString());  
  45.             }else if(param instanceof String){  // 해당 파라미터의 클래스가 String 일 경우(이 경우는 앞뒤에 '(홑따옴표)를 붙여야해서 별도 처리  
  46.             sql = sql.replaceFirst("\\?""'" + param + "'");  
  47.             }else if(param instanceof Map){     // 해당 파라미터가 Map 일 경우  
  48.               
  49.             /* 
  50.              * 쿼리의 ?와 매핑되는 실제 값들의 정보가 들어있는 ParameterMapping 객체가 들어간 List 객체로 return이 된다. 
  51.              * 이때 List 객체의 0번째 순서에 있는 ParameterMapping 객체가 쿼리의 첫번째 ?와 매핑이 된다 
  52.              * 이런 식으로 쿼리의 ?과 ParameterMapping 객체들을 Mapping 한다 
  53.              */  
  54.             List<ParameterMapping> paramMapping = boundSql.getParameterMappings();      
  55.               
  56.             for(ParameterMapping mapping : paramMapping){  
  57.                 String propValue = mapping.getProperty();       // 파라미터로 넘긴 Map의 key 값이 들어오게 된다  
  58.                 Object value = ((Map) param).get(propValue);    // 넘겨받은 key 값을 이용해 실제 값을 꺼낸다  
  59.                 if(value instanceof String){            // SQL의 ? 대신에 실제 값을 넣는다. 이때 String 일 경우는 '를 붙여야 하기땜에 별도 처리  
  60.                 sql = sql.replaceFirst("\\?""'" + value + "'");  
  61.                 }else{  
  62.                 sql = sql.replaceFirst("\\?", value.toString());  
  63.                 }  
  64.                   
  65.             }  
  66.             }else{                  // 해당 파라미터가 사용자 정의 클래스일 경우  
  67.               
  68.             /* 
  69.              * 쿼리의 ?와 매핑되는 실제 값들이 List 객체로 return이 된다. 
  70.              * 이때 List 객체의 0번째 순서에 있는 ParameterMapping 객체가 쿼리의 첫번째 ?와 매핑이 된다 
  71.              * 이런 식으로 쿼리의 ?과 ParameterMapping 객체들을 Mapping 한다 
  72.              */  
  73.             List<ParameterMapping> paramMapping = boundSql.getParameterMappings();  
  74.               
  75.             Class<? extends Object> paramClass = param.getClass();  
  76.             // logger.debug("paramClass.getName() : {}", paramClass.getName());  
  77.             for(ParameterMapping mapping : paramMapping){  
  78.                 String propValue = mapping.getProperty();           // 해당 파라미터로 넘겨받은 사용자 정의 클래스 객체의 멤버변수명  
  79.                 Field field = paramClass.getDeclaredField(propValue);   // 관련 멤버변수 Field 객체 얻어옴  
  80.                 field.setAccessible(true);                  // 멤버변수의 접근자가 private일 경우 reflection을 이용하여 값을 해당 멤버변수의 값을 가져오기 위해 별도로 셋팅  
  81.                 Class<?> javaType = mapping.getJavaType();            // 해당 파라미터로 넘겨받은 사용자 정의 클래스 객체의 멤버변수의 타입  
  82.                   
  83.                 if(String.class == javaType){               // SQL의 ? 대신에 실제 값을 넣는다. 이때 String 일 경우는 '를 붙여야 하기땜에 별도 처리  
  84.                 sql = sql.replaceFirst("\\?""'" + field.get(param) + "'");  
  85.                 }else{  
  86.                 sql = sql.replaceFirst("\\?", field.get(param).toString());  
  87.                 }  
  88.                   
  89.             }  
  90.             }  
  91.               
  92.         }  
  93.            
  94.         logger.debug("=====================================================================");  
  95.         logger.debug("sql : {}", sql);  
  96.         logger.debug("=====================================================================");  
  97.           
  98.         return invocation.proceed(); // 쿼리 실행  
  99.     }  
  100.   
  101.     @Override  
  102.     public Object plugin(Object target) {  
  103.     // TODO Auto-generated method stub  
  104.     return Plugin.wrap(target, this);  
  105.     }  
  106.   
  107.     @Override  
  108.     public void setProperties(Properties properties) {  
  109.     // TODO Auto-generated method stub  
  110.   
  111.     }  
  112.   
  113. }  
spring context xml 설정
  1. <bean id="SsqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  2.         <property name="dataSource" ref="testDS" />  
  3.         <property name="typeAliasesPackage" value="test" />  
  4.         <property name="plugins">  
  5.                       <array>  
  6.                              <bean class="test.LoggingPlugin" />  
  7.                       </array>  
  8.                 </property>         
  9. </bean>  
http://javafactory.tistory.com/entry/Mybatis%EC%9D%98-PlugIn%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%9C-SQL%EB%AC%B8-%ED%8C%8C%EB%9D%BC%EB%AF%B8%ED%84%B0-%EB%B0%94%EC%9D%B8%EB%94%A9-%EB%A1%9C%EA%B7%B8-%EC%B6%9C%EB%A0%A5 참조

'JAVA오픈소스 > mybatis' 카테고리의 다른 글

마이바티스 프로시져 사용법  (0) 2015.11.18
posted by 천상의날개
2016. 1. 28. 15:46 JAVA오픈소스/Spring
ApplicationContextManager java
  1. import org.springframework.beans.BeansException;  
  2. import org.springframework.context.ApplicationContext;  
  3. import org.springframework.context.ApplicationContextAware;  
  4.   
  5.   
  6. public class ApplicationContextManager implements ApplicationContextAware {  
  7.     private static ApplicationContext CONTEXT;  
  8.     public void setApplicationContext(ApplicationContext context) throws BeansException {  
  9.         CONTEXT = context;  
  10.       }  
  11.     public static Object getBean(String beanName) {  
  12.         return CONTEXT.getBean(beanName);  
  13.       }  
  14.     public static Object getBean(Class beanClass) {  
  15.         return CONTEXT.getBean(beanClass);  
  16.       }  
  17. }  
application-context.xml 에 추가
  1. <bean id="springApplicationContext" class="ApplicationContextManager"/>   추가  
사용법
  1. Test bean = (HansolMapper)ApplicationContextManager.getBean(Test.class);  
posted by 천상의날개
2015. 12. 4. 15:18 JAVA오픈소스/Spring

Multiple Transaction Managers with @Transactional

Most Spring applications only need a single transaction manager, but there may be situations where you want multiple independent transaction managers in a single application. The value attribute of the @Transactional annotation can be used to optionally specify the identity of the PlatformTransactionManager to be used. This can either be the bean name or the qualifier value of the transaction manager bean. For example, using the qualifier notation, the following Java code

public class TransactionalService {

    @Transactional("order")
    public void setSomething(String name) { ... }

    @Transactional("account")
    public void doSomething() { ... }
}

could be combined with the following transaction manager bean declarations in the application context.

<tx:annotation-driven/>

    <bean id="transactionManager1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        ...
        <qualifier value="order"/>
    </bean>

    <bean id="transactionManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        ...
        <qualifier value="account"/>
    </bean>

In this case, the two methods on TransactionalService will run under separate transaction managers, differentiated by the "order" and "account" qualifiers. The default <tx:annotation-driven> target bean name transactionManager will still be used if no specifically qualified PlatformTransactionManager bean is found.

 

참조 URL : https://www.lesstif.com/pages/viewpage.action?pageId=20774954

posted by 천상의날개