'myBatis'에 해당되는 글 2건

  1. 2018.06.11 스프링 db, 마이바티스 세팅 (java config)
  2. 2018.05.14 spring-mysql 연동 (xml)
반응형


# 사용 환경

스프링 버전 : 4.3.2

db : mysql


본 포스팅에서는 mysql, mybatis 세팅 방법을 기록한다.


1. pom.xml 수정

 - pom.xml 파일에 아래의 내용을 추가한다. db, mybatis 관련 내용이 모두 담겨있다.

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
<!-- MySQL -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>
 
<!-- MyBatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
</dependency>
 
<!-- MyBatis-Spring -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
</dependency>
 
<!-- Spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
cs



2. 자바 설정파일 작성

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
31
32
33
34
35
36
37
@Configuration
public class DatabaseConfiguration {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    @Bean
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource source = new DriverManagerDataSource();
        source.setDriverClassName("com.mysql.cj.jdbc.Driver");
        // 자바 설정으로 쓸 때에는 url에 &을 &amp; 로 치환하면 에러나더라.        
        source.setUrl("jdbc:mysql://localhost:3306/test_db?serverTimezone=UTC&useSSL=false");
        source.setUsername("user01");
        source.setPassword("1234");
        
        return source;
    }
    
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:mybatis/config/mybatis-config.xml"));
        sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources("classpath:mybatis/mapper/*.xml"));
        
        return sqlSessionFactoryBean.getObject();
    }
    
    
    @Bean
    public SqlSession sqlSession() throws Exception {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory());
        return sqlSessionTemplate;
    }
    
}
 
cs
1 : 이 파일이 설정 파일임을 알리는 어노테이션
23-24 : 마이바티스 설정파일, 맵퍼 xml의 위치.. 없이 세팅도 가능하지만 일단 추가.

3. 마이바티스 xml 파일들 추가
 - 아래와 같이 경로를 생성하고 파일을 넣어둔다. (경로는 2번에서 설정한 경로에 맞춘 것)
각 파일들의 내용은 아래와 같다
 3-1. mybatis-config.xml
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
 
<configuration>
    
</configuration>
cs

 

 3-2. test-mapper.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<!-- 사용할 인터페이스의 경로 -->
<mapper namespace="com.post.javaconfig.dao.TestDao">
 
</mapper>
  
cs

 - 인터페이스 파일과 매칭이 되어야 에러가 나지 않는다.

 3-3. TestDao 인터페이스 생성
1
2
3
4
public interface TestDao {
    @Select("select 1")
    int test();    
}
cs
- 쿼리는 xml 파일에서 작성 할 수도, 인터페이스에서 직접 작성할 수도 있다.
- 아래 메소드를 호출하면 어노테이션에 적힌 쿼리 실행 결과가 리턴된다.

아래 이미지는 세팅된 파일들의 트리이다.



여기까지 세팅이 끝났다면 db, mybatis 연동이 끝이다.
아래는 기본 생성되는 HomeController 파일에 확인용 코드를 추가한 것이다.
서버를 실행하고 루트 페이지로 접속하면 sts상에 쿼리 결과가 찍힐 것이다.

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
31
32
33
34
35
36
@Controller
public class HomeController {
    
    // 요기 추가
    @Autowired
    private SqlSession sqlSession;
    
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        
        // 테스트를 위해 추가
        // ********************************
        TestDao testDao = sqlSession.getMapper(TestDao.class);
        System.out.println(testDao.test());        
        // ********************************
        
        logger.info("Welcome home! The client locale is {}.", locale);
        
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        
        String formattedDate = dateFormat.format(date);
        
        
        model.addAttribute("serverTime", formattedDate );
        
        return "home";
    }
    
}
cs




Posted by NULL..
,
반응형

** mysql이 설치되어있다는 전제로 진행



1. pom.xml 파일에 dependency 추가

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
        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
 
        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
  
        <!-- MyBatis-Spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
 
        <!-- Spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
cs


<version>에 ${org.springframework-version}라고 쓰여 있는 것은

pom.xml 상단에 설정된 프로퍼티를 따르겠다는 것



2. root-context.xml 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<bean id="dataSources" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test_db?serverTimezone=UTC&amp;useSSL=false"/>
        <property name="username" value="user01" />
        <property name="password" value="1234" />
    </bean>
        
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSources" />
        <property name="configLocation" value="classpath:mybatis/config/mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml" />
    </bean>
    
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
cs


beans 안에 위의 코드를 위치 시킨다. 몇몇 줄에 대한 설명을 첨부한다.

#1. 데이터베이스 구현체.. 프로퍼티로 데이터베이스 정보들을 넣어주어야 함

#3. 데이터베이스 url.. 기본적인 형식은 다음과 같다.

 - jdbc:mysql://[ip]:[port]/[database]?serverTimezone=UTC

 - ip에는 로컬에서 하기 위해 편하게 localhost를

 - port는 mysql 설치시 변경하지 않았으면 3306이다.

 - database는 테스트를 위해 test_db를 생성해두었다

#8. mybatis를 사용하기 위한 팩토리 생성

#10. mybatis 설정 파일의 경로를 지정해준다.

#11. mybatis맵퍼 파일들의 경로를 지정해준다

#14. spring-mybatis를 이용하면 세션관리를 알아서 잘 해준다. 이를 이용하기 위한 설정



3. mybatis xml 파일 생성

 - root-context.xml 을 수정할 때 마이바티스 설정 파일들의 경로를 지정해줬었다. 없으면 에러가 날 것이므로 해당 파일들의 경로 및 파일을 생성해준다.


3-1. 경로 생성 및 파일 생성

 - root-context.xml 수정할 때 [classpath:mybatis/mapper/*.xml]라는 값을 준 적이 있다. 해당 값은 다음의 의미를 가진다.

 [classpath:] : src/main/resources 경로

 [mybatis/mapper/*.xml] : mybatis/mapper/ 아래의 모든 xml파일


 - 아래 첨부한 이미지와 같이 경로와 파일을 생성해준다.


3-2. xml 파일 생성

 - mybatis-config.xml

 - 마이바티스가 제공하는 여러 설정을 지정할 수 있는 파일이다.

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
  
<configuration>
    
</configuration>
cs


 - user-mapper.xml

 - sql문을 입력할 파일이다.

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<!-- 사용할 인터페이스의 경로 -->
<mapper namespace="com.security.mysql.dao.UserDao">
 
 
</mapper>
cs

 #7. 맵퍼와 연결할 인터페이스. 혹은 클래스의 경로이다. 자신의 환경에 맞추어 설정하면된다. 본 설정에서는 인터페이스를 이용해 간단하게 이용해 볼 것이다.

4. 데이터베이스에 쿼리 날리기

 - 스프링 프로젝트를 생성하면 기본적으로 설정되는 파일 내에서 테스트를 해볼 것이다.

 - 쿼리 작성을 위해 데이터베이스에 미리 간단한 테이블을 생성해두었다.

 - 내용은 아무것도 넣지 않은 상태이다.

1
2
3
4
5
6
7
8
CREATE TABLE `user` (
    `idx` INT(11NOT NULL AUTO_INCREMENT,
    `user_id` VARCHAR(50NOT NULL,
    `user_pwd` VARCHAR(50NOT NULL,
    PRIMARY KEY (`idx`)
)
ENGINE=InnoDB
;
cs


 - 3번에서 파일 생성을 완료 했다면 디렉토리 구조는 아래와 같을 것이다.


4-1. 쿼리 작성

 - 위에서 생성한 user 테이블에 입력된 데이터 수를 가져오는 쿼리를 만들어 볼 것이다.

 - 쿼리 작성은 인터페이스와 맵퍼 두 파일 모두에서 할 수 있다.

 - 맵퍼 파일을 이용할 경우 여러 옵션 추가나 if문 등도 사용할 수 있다.


 - 인터페이스에서 작성하는 방법은 아래와 같다

1
2
3
4
5
6
public interface UserDao {
    
    @Select("select count(*) from user")
    int getUserCnt();
    
}
cs

 #3. 어노테이션을 이용해 쿼리를 인터페이스에서 바로 작성한다.

 #4. 해당 쿼리를 호출할 메소드명


 - 맵퍼를 이용하는 방법은 인터페이스, 맵퍼파일을 모두 수정해야 한다.

 - UserDao.java

1
2
3
4
5
public interface UserDao {
    
    int getUserCnt();
    
}
cs

 #3. 맵퍼파일의 id를 메소드 이름 설정하고 resultType를 반환값으로 설정


 - user-mapper.xml

1
2
3
4
5
6
7
8
9
<mapper namespace="com.security.mysql.dao.UserDao">
 
    <select id="getUserCnt" resultType="int">
    
        select count(*) from user 
        
    </select>
 
</mapper>
cs

 #3. getUserCnt라는 이름의 select문이고 반환타입은 int이다.

 #5. 쿼리



4-2. 쿼리 호출

 - 4-1에서 작성한 쿼리를 호출해 볼 것이다. 작성방법 두 가지 중에 어떤 것을 사용했더라도 호출 방법은 동일하다. 프로젝트 생성시 기본적으로 만들어지는 HomeController.java 파일에 코드를 추가해 볼 것이다.

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
@Controller
public class HomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    @Autowired
    private SqlSession SqlSession;
    
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
        
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        
        String formattedDate = dateFormat.format(date);
        
        UserDao userDao = SqlSession.getMapper(UserDao.class);
        int userCnt = userDao.getUserCnt();
        System.out.println("userCnt : " + userCnt);
 
        model.addAttribute("serverTime", formattedDate );
      
        return "home";
    }
    
}
cs
- HomeController.java 생성시에 없던 코드는 굵게 표시해두었다.

 #6~7. root-context.xml에 생성해둔 sqlSession을 이용하기 위함

 #18~20. 쿼리 실행한 값을 userCnt에 담고, 받아온 값을 확인하기 위함



여기까지 작성한 후 서버를 실행하고 기본 페이지로 접속을 하면 아래와 같은 내용이 sts 콘솔에 찍힐 것이다.

 



본 글은 간단하게 세팅하는 방법만 기록해두었다.

여러 옵션을 사용하는 방법에 대한 공부가 필요하다..



Posted by NULL..
,