이미 현업에서는 자주 사용하지만 따로 정리하지는 않아서 이번기회에 정식 레퍼런스를 보면서 내용을 찾아보았다

스프링 트랜잭션 처리

https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction-declarative-attransactional-settings

 

Data Access

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies (such as JDBC, Hibernate, or JPA) in a consistent way. This lets you switch between the aforementioned persistence technologies fairly easily, a

docs.spring.io

The @Transactional annotation is metadata that specifies that an interface, class, or method must have transactional semantics (for example, "start a brand new read-only transaction when this method is invoked, suspending any existing transaction"). The default @Transactional settings are as follows:

 

  • The propagation setting is PROPAGATION_REQUIRED.
  • The isolation level is ISOLATION_DEFAULT.
  • The transaction is read-write.
  • The transaction timeout defaults to the default timeout of the underlying transaction system, or to none if timeouts are not supported.
  • Any RuntimeException triggers rollback, and any checked Exception does not

스프링 트랜잭션 처리중에 예외가 발생했을때 명시적으로 아래의 옵션들을 사용해서 롤백 여부를 결정할수 있다

rollbackFor 롤백을 실행시키는 예외 클래스 목록들
rollbackForClassName 롤백을 실행시키는 예외 클래스 이름들
noRollbackFor 롤백을 실행시키지 않는 예외 클랙스 목록들
noRollbackForClassName 롤백을 실행시키지 않는 예외 클래스 이름들

 

자바 vs 스프링 트랙잭션 처리에 대한 오해

구글에서 자바 트랜잭션 처리로 검색해 보면 Checked vs Unchecekd exception 에 대해 비교하고 unchecekd exception 에 대해 rollback 을 시행한다고 적혀있는 글을 많이 볼수있다.

 

이는 염언히 틀린말이다. 자바에서는 기존벅으로 트랜잭션에 대한 기본적인 처리 메커니즘을 제공하지 않으므로 Checked 이든 Unchecked 이든 프로그래머가 어떻게 프로그램을 짜느냐에 달려있다. 즉 Unchecked 에 롤백하는 메커니즘은 스프링 프레임워크를 사용할때 적용되는 기본 세팅이지 다른 프레임워크 혹은 프레임워크를 사용하지 않고 순수 자바 SDK 에서 제공하는 인터페이스로만 DB처리를 할경우 맞지 않는 말이된다. 

 

이는 자바=스프링을 동일시하는데 발생해서 불러오는 자바 개발자들 사이에서 불러오는 흔한 오해라고 생각한다.

하이버네이트는 내부적으로 두종류의 캐쉬를 지원하는데 하나는 First-level cache 이고 다른 한종류는 Second-level Cache 이다

 

First-level cache?

대부분의 ORM (Object Relational Mapping) 프레임워크가 지원하는것처럼 하이버네이트또한 일차적 캐쉬를 지원한다. 

일차캐쉬는 Hibernate 의 Session 단계에서 지원하는 캐쉬로 가장 비싼 연산작업중 하나인 데이터베이스와의 대화를 줄여주기 위해 존재한다. Session 안에서 동작하는 캐쉬이기 때문에 Session 이 종료되면 캐쉬도 같이 사라지게 된다.

 

Second-level cache?

First level cache 이 세션 단계에서의 캐쉬라면 second level cache 는 session factory 단계에서 지원하는 캐쉬로 session factory 에서 생성되는 session 간에 공유가 된다. 

 

 

표로 다시 정리하면

  First Level  Second Level
범위 Session  Session Factory (all sessions) 
기본 활성화 O X
설정 따른 설정 필요없음 설정필요
캐쉬 백엔드에 따라 다른 설정 추가 필요

 

동시성 캐쉬 전략

이름  
READ_ONLY 읽기에 대한 캐쉬를 생성한다. 설정값 같이 어플리케이션이 시작되고 변화하지 않는 값에 대해 사용
NONSTRICT_READ_WRITE READ_WRITE 와 비슷하지만 때때로 데이터를 읽는 경우에 최신의 데이터를 가지고 오지 않을수도 있늠점에 유의해햐한다. 
어플리케이션이 같은 데이터에 대해 접근하는 일이 많이 없고 강한 트랜잭션 격리가 필요없는 경우 사용
READ_WRITE 읽기와 쓰기에 대해 캐쉬를 생성한다. Seriazliable 트랜잭션 격리수준은 적용되지 않는다
TRANSACTIONAL
트랜잭션 대한 캐쉬를 지원한다. Seriazliable 트랜잭션 격리.
TA Transaction Provider 와 같이 사용하여 분산 트랙잭션을 사용하는 경우 사용하면 좋을 거 같다 

 

Entity 에 대해 캐쉬 사용할때 샘플코드

@Entity(name = "Company")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public static class Company {

}

 

참조: 

1. https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#caching

'Java > JPA' 카테고리의 다른 글

JPA Cascade Types  (0) 2021.12.19

JPA를 사용해서 엔티티간의 관계를 설정할때 아래와 어노테이션을 작성하는 일이 많은데 어떤 의미를 가지고 있는지 알아보자

@OneToMany(cascade={CascadeType.REFRESH, CascadeType.MERGE}, fetch = FetchType.LAZY)

 

먼저 각각의 CaseType에 들어가기전에 영속성 컨텍스트와 JPA의 상태에 대한 선행지식이 필요하다

 

Persistence Conxtet (영속성 컨텍스트)

공식문서의 정의를 참조해보자 

 

EntityManager (Java(TM) EE 7 Specification APIs)

Interface used to interact with the persistence context. An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. W

docs.oracle.com

A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The 
EntityManager
 API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.

어렵게 정의되어 있지만 간단하게 요약하자면 영속성 컨텍스트가 영속성 컨텍스트안에 있는 엔티티들의 변화를 추적하고 관리한다는 이야기다.

 

엔티티 객체의 상태

상태 설명
Transient 엔티티 객체가 데이터베이스에 아직 저장되기 전의 상태 
Persistent 엔티티 객체가 데이터베이스에 저장된 상태
Detached Persistent 상태였던  엔티티 객체가 더이상 영속성 컨텍스트에 속해있지 않는 상태

JPA의 동작들

동작 설명 특징
Save 하이버네이트 구현체에만 있는 기능 Persist 와 같은 기능.  Persist 는 생성된 ID 를 돌려주지 않으나 Save 는 돌려준다
Persist 엔티티를 영속성 컨텍스트에 포함시킨다 1. 엔티티가 Transient 상태라면 엔티티는 Persistent 상태가 된고 관련 동작들을 전파한다. (PERSIST, ALL로 설정된 경우)
2. 엔티티가 이미 Persistent 상태라면 엔티티에 직접적인 영향은 없다. 그러나 관련 동작들은 여전히 자식으로 전파된다
3. 엔티티가 Detached 상태라면 에러를 발생시킨다
Merge Persistent 상태의 엔티티 객체를 Deatched 상태의 객체의 값들로 업데이트한다  
Update 하이버네이트에만 존재하는 동작으로 Merge 와 같은 동작을 수행한다  
SaveOrUpdate 하이버네이트에만 존재하는 동작으로   

Cascade 종류

 

 

Hibernate ORM 5.6.3.Final User Guide

Fetching, essentially, is the process of grabbing data from the database and making it available to the application. Tuning how an application does fetching is one of the biggest factors in determining how an application will perform. Fetching too much dat

docs.jboss.org

JPA 표준에 사용하면 아래와 같이 6가지 Cascade Type 있다

종류 특징
ALL 아래에 기술된 모든 동장들을 자식 엔티티에게 전파한다
PERSIST JPA의 Persist 동작 (save, persist )을 부모 엔티티에서 자식 엔티티에게 전파된다
MERGE 부모 엔티티가 업데이트 될때 자식 엔티티들도 업데이트 된다
REMOVE 자식 엔티티들을 부모 엔티티 삭제시 동시에 삭제한다
REFRESH 데이터베이스로부터 데이터르 다시 읽어 들이는 refresh 동작을 부모에서 자식 엔티티로 전파
DETACH Detach 를 부모에서 자식 엔티티로 전파한다

하이버네이트에만 존재하는 CaseCade Type

종류 특징
REPLICATE Replicate 를 사용할떄 자식엔티티에게도 같은 동작을 전파한다.
**자동생성되는 ID 사용하지 않고 엔티티를 복제할 필요가 있을때 사용하면 좋다.
SAVE_UPDATE 하이버네이트 구현체의 save, update, saveOrUpdate 동작을 수행시에 자식 엔티티에게 같은 동작을전파한다
LOCK 이미 Detached 된 부모 엔티티 객체를 다시 영속성 객체에 추가시에 자식엔티티도 같이 추가된다

 

참조:

1. https://docs.jboss.org/hibernate/orm/5.6/userguide/html_single/Hibernate_User_Guide.html

2. https://stackoverflow.com/questions/161224/what-are-the-differences-between-the-different-saving-methods-in-hibernate

'Java > JPA' 카테고리의 다른 글

JPA & Hibernate Cache  (0) 2022.01.19

어플리케이션을 구동하기 위해 사용되는 설정값들을 어플리케이션이 돌아가는 플랫폼안에서 보통 환경변수 혹은 파일안에 저장해두고 쓰는데 어플리케이션 설정값을 Zookeepr, AWS Secrets 과 같은 외부 서비스에서 불러들이거나 보안을 위해 설정값들을 메모리 안에서만 저장이 필요한 경우에 활용 가능한 방법이다.

Spring boot 에서 만 활용 가능한 방법

EnvironmentPostProcessor 를 활용

public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, 
      SpringApplication application) {
        PropertySource<?> system = environment.getPropertySources()
          .get(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);

        Map<String, Object> prefixed = names.stream()
          .collect(Collectors.toMap(this::rename, system::getProperty));
        environment.getPropertySources()
          .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));
    }

}

Spring boot 와 Spring boot를 사용하지 않는 환경에서 활용 가능한 방법

ApplicationContextInitializer 를 활용한 방법

먼저 아래와 같이 프로퍼티 값을 오버라이드 하는 코드를 작성해준다.

public class PropertyOverrideContextInitializer
  implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableWebApplicationContext applicationContext) {
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        MyConfigProps configProps = Binder.get(environment).bind("my-config", MyConfigProps);
        System.out.println(configProps.getHomekey());
    }
  }

여기서 네가지 방법으로 어플리케이션에 적용 가능하다

1. web.xml 안에 있는 contextInitializerClasses 에 추가 혹은 상응하는 Java Config (Spring MVC)

    <context-param>
        <param-name>contextInitializerClasses</param-name>
        <param-value>com.xxxx.PropertyOverrideContextInitializer</param-value>
    </context-param>

 

자바로 설정시에 

 

@ContextConfiguration(initializers = PropertyOverrideContextInitializer.class)
public class AppConfig {

}

스프링만 사용시 

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
MyAppContextInitializer initializer = new MyAppContextInitializer();
initializer.initialize( ctx );

ctx.register( com.my.classpath.StackOverflowConfiguration.class );
ctx.refresh()

JobLauncher launcher = context.getBean(JobLauncher.class);

 

2. META-INF/spring.factories 추가하여 자동 설정 추가 (Spring Boot) 

org.springframework.context.ApplicationContextInitializer=
org.springframework.boot.context.PropertyOverrideContextInitializer

3. 어플리케이션 추가 실행코드에 추가코드에 추가하는 방법 (Spring boot)

application.addInitializers(PropertyOverrideContextInitializer.class);
application.run(args);

혹은

new SpringApplicationBuilder(YourApp.class)
    .initializers(PropertyOverrideContextInitializer.class);
    .run(args);

4. context.initializer.classes 프라퍼티 설정 (Spring boot)

context.initializer.classes=com.xxxx.PropertyOverrideContextInitializer

참조

  1. https://www.baeldung.com/spring-tests-override-properties
  2. https://stackoverflow.com/questions/35217354/how-to-add-custom-applicationcontextinitializer-to-a-spring-boot-application
  3. https://stackoverflow.com/questions/35048164/spring-applicationcontextinitializer-and-properties
  4. https://stackoverflow.com/questions/13288841/applicationcontextinitializer-in-a-non-web-spring-context

3.x 버전대가 2016년 12월을 기준으로 종료된다기에 기존 3.2.9 버전의 스프링에서 4.x 버전대로 마이그레이션을 시도하였다.


다행히도 기존 진행하는 프로젝트에서 3.x 


Pom.xml 에서 주의해서 

<properties> <java-version>1.8</java-version> <org.springframework-version>4.3.5.RELEASE</org.springframework-version> <org.springframework-security-version>4.2.0.RELEASE</org.springframework-security-version> </properties> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- MappingJacksonJsonView --> <!-- <dependency> --> <!-- <groupId>org.codehaus.jackson</groupId> --> <!-- <artifactId>jackson-mapper-asl</artifactId> --> <!-- <version>1.9.13</version> --> <!-- </dependency> --> <!-- <dependency> --> <!-- <groupId>org.codehaus.jackson</groupId> --> <!-- <artifactId>jackson-core-asl</artifactId> --> <!-- <version>1.9.13</version> --> <!-- </dependency> -->


다른 Configuration  파일들도 schemaLocation 부분에 수정을 해주었다. xxx-3.0.xsd 로 로된부분을

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    					http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        
</beans>


자동으로 인식하도록 숫자부분을 아래와 같이 변경했다.

http://www.springframework.org/schema/context/spring-context.xsd



resources 부분도 아래와 같이 변경했다.

<mvc:resources location="/public/" mapping="public/**"/>
<mvc:resources location="/css/" mapping="css/**"/>
<mvc:resources location="/images/" mapping="images/**"/>
<mvc:resources location="/js/" mapping="js/**"/>


JacksonJsonView를 사용하지 않기때문에 주석처리하였다 사용하기 위해서는 2버전을 사용해야한다.

<!-- <bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> -->


이렇게 하여 마이그레이션이 완료되었다.

마이그레이션은 프로젝트 마다 케이스바이 케이스기 떄문에 스프링버전에 의존하는 라이브러리가 없나 살펴보아야한다.

더 자세한 마이그레이션 관련은 아래에 링크된 스프링 공식홈페이지의 깃허브를 참조한다. 


참조:

1. https://github.com/spring-projects/spring-framework/wiki/Migrating-from-earlier-versions-of-the-spring-framework

'Java > Spring Framework' 카테고리의 다른 글

Spring 한글설정  (0) 2015.03.19
Spring AOP  (0) 2015.01.19
스프링 스터디 - 의존성 주입 대상  (0) 2015.01.14
스프링 학습 개발 도구 설치  (0) 2015.01.13
프레임 워크 배우기 좋은 웹사이트  (0) 2014.11.04

스프링 프로파일을 사용해서 환경별로 다른 설정이 가능하다 .

* Maven 프로파일 설정과는 별개이므로 주의 Maven 프로파일 설정은 (https://www.lesstif.com/pages/viewpage.action?pageId=14090588) 참조

 

 

먼저 properties 파일들을 development 와 

spring 환경을 설정하는 방법은 2가지 방법이 있다.

 

 

1. 빌드시 전달하는 JVM property 

 

e.g)

java -jar -Dspring.profiles.active=dev

 

 

2. web.xml에서 active-profile 설정

<context-param> 	<param-name>spring.profiles.active</param-name> 	<param-value>production</param-value> </context-param>

3. catalina.sh 에 직접 설정 

JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=local"

 

4. catalina.properties 에 추가 (D를 빼는 것 주의)

spring.profiles.active=dev

 

 

** 중복된 설정 우선순위

현재 삽질하며 확인한 결과 web.xml 을 최우선시하고 tomcat 환경설정에 직접 넣은 값은 값이 있을 경우 무시한다

 

이제 spring.profiles.active 에 따라 다른 properties 파일을 읽는 설정을 해주어야한다. 

아래코드를 응요해서 자신에게 맞는 방법을 선택하자 

필자는 development.properties 와 production.properties 를 classpath 아래 두었다.

 

<bean id="config" 	class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 	<property name="locations"> 		<list>				 			<value>classpath:/#{systemProperties['spring.profiles.active']}.properties 			</value> 		</list> 	</property> </bean>

 

* 추가팁 로벌 spring 환경 설정 톰캣에서 사용할 경우 설정 방법 

1. 이클립스 환경 톰캣에서 지정

 

 

 

참고

 

1. http://stackoverflow.com/questions/15814497/setting-spring-profile-variable

2. http://jdm.kr/blog/81

 

스프링을 사용하다보면 webapps 폴더안에 파일들에 대해 접근해야할 필요가 있다. 

Servletcontext 를 이용한 접근 방법이 있으나 이방법은 Servletcontext 에 의존적이라는 단점이 있다. 

특정 동작만을 위한 모듈을 덧붙일 경우 다른 방법이 필요한데 스프링에서는 이방법 또한 제공한다. 바로 코드로 보자 


import java.io.IOException;
import java.io.InputStream;

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public class ArbitraryResourceLoader implements ResourceLoaderAware {
    private ResourceLoader resourceLoader;

    public void test() throws IOException {
        Resource resource = resourceLoader.getResource("file:webapps/config.txt");
    	InputStream is = resource.getInputStream();
    	try{
    		int i=0;
            while((i=is.read())!=-1)
            {
               char c=(char)i;
               System.out.print(c);
            }
        }catch(IOException e){
        	 e.printStackTrace();
         }finally{
            
           if(is!=null)
            is.close();
         }
    }

	@Override
	public void setResourceLoader( ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;		
	}

}


그리고 빈설정 파일에 아래와 같이 설정해준다 class 경로 같은 경우는 자기자신의 프로젝트에 따라 바뀔것이다

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 
	 <bean id="arbitraryResourceLoader" class="org.test.sample.ArbitraryResourceLoader"/>

</beans>


JavaConfig로도 쉽게 응용할수 있으리라 생각한다. 

프로젝트를 진행하다보면 파일안에 Properties 파일들을 저장해놓고 사용하는 일들이 자주 생긴다. 

가장 간단하게 사용하는 방법은 XML 혹은 JSON을 특정 경로에 넣고 파싱하는 방법이 있으나 설정파일을 사용하는 곳이 많아질 경우 복잡하다. 

스프링 프레임워크는 프레임워크 단에서 Properties 를 설정하는 방법을 가지고 있다.


Spring 설정 xml 안에 아래와 같은 설정을 추가한다. 

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd">
	<context:component-scan base-package="com.tutorialspoint" />

	 <!-- context:property-placeholder location="classpath:database.properties"  /!-->
	<context:property-placeholder location="/WEB-INF/*.properties" />

</beans>


그럼 자동으로 WEB-INF 경로 아래에 있는 *.properties 밸류들이 로드된다.


스프링 내에서 사용하기 위해선 아래와 같이 사용한다.

@Component
class MyClass {
  @Value("${my.property.name}")
  private String[] myValues;
}


만약 위의 설정 방법이 안된다면 수동으로 빈을 생성해준다. 


<bean id="myProperties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath*:my.properties</value>
    </list>
  </property>
</bean>

그리고 Resource 파일을 이용해서 불러들인다. 

@Component
class MyClass {
  @Resource(name="myProperties")
  private Properties myProperties;

  @PostConstruct
  public void init() {
    // do whatever you need with properties
  }
}



* 추가 

Project 진행시에 보통 개발, 테스트, 프로덕션 서버별로 배포를 다르게한다. 

각각의 환경마다 다른 설정값을 가지므로 배포시마다 사용하는 property 의 이름을 변경해주는 것은 여간 귀찮은 일이 아니다

다행이 스프링에서는 Profile 이라고 환경마다 다른 설정을 사용할수 있는 기능이 이미 내장되어있다. 

경로 부분을 지정해주고 ${spring.profiles.active} 코드를 넣어주면 Profile에 따라 설정값이 다르게 쓰인다. 

아래는 예제코드를 보면 profile 을 사용하시는 분들이라면 바로 이해가 갈것이다. 

<context:property-placeholder location="classpath:${spring.profiles.active}.properties" />



참고: 

1. http://jijs.tistory.com/entry/spring-%EC%84%A4%EC%A0%95-xml%EA%B3%BC-%EC%86%8C%EC%8A%A4%EC%BD%94%EB%93%9C%EC%97%90%EC%84%9C-properties-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

2. http://stackoverflow.com/questions/9259819/how-to-read-values-from-properties-file

3. http://nkjava.blogspot.kr/2013/07/springmvc-read-property-in-jsp.html

4. http://stackoverflow.com/questions/10669474/load-properties-file-in-spring-depending-on-profile

스프링으로 mybatis 를 사용할 경우 디폴트 설정만으로 충분한 경우가 많기때문에 따로 설정파일을 쓸경우를 제외하고는 디폴트 설정으로 쓰는편이다.

스프링의 같은경우 mybatis 설정들을 대부분 자동으로 해주기때문에 SqlSessionFactoryBean 에 mapper위치정도만 설정해놓고 자주 사용하는 편이자 


기본 스프링 설정파일을 아래와 같이 지정한후 보통 resources/mapper or resources/mybatis 아래에 둔다. 파일명은 mapper-config.xml 로 해두었다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
                        

 
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />        
        <property name="configLocation" value="classpath:/mapper/mybatis-config.xml" />        
		<property name="mapperLocations" value="classpath*:/mapper/**/*_SQL.xml" />
        
    </bean>
     
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSession"/>
    </bean>    
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="인터��이스로 맴퍼  자동맵퍼설정패키지" />
	</bean>
        
</beans>


classpath 위치 아래에 아래와 같이 만들어주어서 추가적인 설정을 해주면된다. 예제의 경우는 classpath 아래 mapper 폴더안에 mybatis-config.xml 을 사용했다. 


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
                        

 
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />        
        <property name="configLocation" value="classpath:/mapper/mybatis-config.xml" />        
		<property name="mapperLocations" value="classpath*:/mapper/**/*_SQL.xml" />
        
    </bean>
     
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSession"/>
    </bean>    
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="인터��이스로 맴퍼  자동맵퍼설정패키지" />
	</bean>

<typeHandlers>
  <typeHandler handler="org.mybatis.example.ExampleTypeHandler"/>
</typeHandlers>
        
</beans>


이클립스 기준 톰캣 7.x 버전으로 설정


CENTOS 기준


$CATALINA_HOME/catalina.bat 파일 안에 


CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"


* 중요 

카탈리나 아래명령어와 함께 재실행

catalina.sh jpda start



안에 위에것을 추가해주고 톰캣을 재시작해준다. 

* 8000은 자기 포트번호에 맞게 변경한다.


* 당연한 이야기지만 서버측에서도 포트번호 8000번을 열어주어야한다. 보안이 강화된 환경에서 라우터 또는 방화벽에서 포트번호를 막을수도 있다. 필자는 이것때문에 원인을 찾지 못하고 삽질을.. 



이제 이클립스를 설정해주어야한다.

Run - Debug Configurations 


Remote Java Application 항목에서 오른쪽 클릭후 New를 클릭해준다


Project를 디버깅하고자는 프로젝트를 선택하고


서버가 존재하는 아이피를 클릭하고

위에 카탈리나 bat파일에서 입력한 포트번호를 입력한다




설정완료 후 Debug 버튼을 클릭하면 디버깅 Perspective 로 전환되는 것을 볼수 있다.


참고자료:

http://wonzopein.com/56

http://bryan7.tistory.com/143

http://stackoverflow.com/questions/3835612/remote-debugging-tomcat-with-eclipse


+ Recent posts