티스토리 뷰
Mybatis
Mybatis는 JDBC로 처리하는 코드와 파라미터 설정 및 결과 매핑을 대신해주는 퍼시스턴스 프레임워크다. 동적 SQL, POJO 매핑 등의 기능을 제공한다.
Mybatis 설정
Spring boot에서 Mybatis를 이용해 MySQL을 연동하기 위해선 먼저 아래와 같이 Maven에 Dependency를 설정해줘야한다.
...
<!-- Mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- Driver-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
...
Mybatis와 MySQL을 연동하기 위한 connector를 dependency로 추가했다. 이제 Database를 어떤 것을 사용할 지 property에 명시를 해야한다. 아래는 spring 프로젝트 생성 시 default로 있는 application.properties에 추가한 내용이다.
...
spring.db1.datasource.url=jdbc:mysql://localhost:3306/test_db
spring.db1.datasource.username=test_user
spring.db1.datasource.password=test_pw
spring.db1.datasource.driverClassName=com.mysql.jdbc.Driver
...
어떤 Database를 사용할 지 주소를 url에 명시하고, Database에 접근할 때 필요한 id, password를 명시해놨다. 그리고 mysql에 접근할 driver를 명시해놨다.
이제 configuration class에서 Datasource, SqlSession, Template Bean을 설정해줘야 한다. 우선 아래의 코드를 보자.
@Configuration
@MapperScan(
basePackages="com.example.demo",
sqlSessionFactoryRef = "mysqlSessionFactory",
sqlSessionTemplateRef = "mysqlSessionTemplate")
public class DemoConfig {
@Bean(name="mysqlDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.db1.datasource")
public DataSource dbDataSource()
{
return DataSourceBuilder.create().build();
}
@Bean(name="mysqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("mysqlDataSource")DataSource dataSource) throws Exception
{
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
// annotation이 아닌 xml을 통한 mapping을 할거면 아래와 같이 사용
//PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/abc.xml"));
return sessionFactoryBean.getObject();
}
@Bean(name="mysqlSessionTemplate")
@Primary
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception
{
return new SqlSessionTemplate(sqlSessionFactory);
}
}
@MapperScan annotation을 명시해 준 class는 basePackages로 지정한 곳에 존재하는 @Mapper로 명시된 interface를 스캔한다. sqlSessionFactoryRef, sqlSessionTemplateRef 속성은 Database를 여러개 연결할 때 구분해주기 위한 속성이다. 두 개 이상의 MapperScan class 사용 시 명시를 안하면 오류가 난다. @Primary는 Database가 두 개 이상 있을 때 어떤 Database를 첫 번째로 사용할 것인지 지정하는 annotation이다.
이제 basePackages 속성에 지정한 package에 Mapper interface를 만들어보자.
@Mapper
public interface userMapper {
@Select("SELECT * FROM user WHERE uid > #{uidNumber}")
List<userDTO> getUsersOverUID(@Param("uidNumber")int uidNumber);
}
Mapper는 반드시 interface로 구현해야 한다. @Select annotation을 이용해 user라는 이름의 table에서 uid 값이 매개변수 uidNumber보다 큰 데이터를 userDTO의 List로 반환하고 있다. 저번 포스팅에서 DTO에 관해서 간단히 적었는데, Database를 이용할 때 값을 받아올 class이다. userDTO는 아래 코드처럼 구현된다.
public class userDTO {
private BigInteger uid;
private String id;
private String pw;
private Timestamp date;
private Timestamp modDate;
private String nickname;
// 아래에 public으로 getter setter 구현 (길어서 생략)
}
위와 같이 data와 getter, setter로만 돼있는 순수 자바 객체(POJO)에 query문 결과가 담겨 List로 반환되는 것이다. 이것을 이용하려면 아래 DAO 클래스처럼 사용하면 된다.
@Repository("userDAO")
public class userDAO {
@Autowired
@Qualifier("userMapper")
private userMapper userMapper;
public List<String> getUserIDs()
{
return userMapper.getUsersOverUID(0)
.stream()
.map(user->user.getId())
.collect(Collectors.toList());
}
}
위처럼 @Autowired annotation으로 userMapper를 주입받아서 query문을 사용할 수 있다. getUserIDs 함수 내부의 복잡해보이는 호출은 C#의 linq와 비슷한 역할을 하는 것이니 참고하자.
DAO를 Service나 Controller에서 주입받아서 얻어온 내용을 아래 그림 1처럼 테스트 view에 띄워볼 수 있다. 이 내용은 저번 포스팅과 겹치므로 생략하겠다.
참조
Mybatis 예제
blogId=islove8587&logNo=220989983084&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F
https://blog.naver.com/PostView.nhn?
https://gs.saro.me/#!m=elec&jn=778
공식 레퍼런스
http://www.mybatis.org/spring/ko/getting-started.html
Mybatis 퀵 가이드
http://www.baeldung.com/mybatis
MySQL & jdbc 연결 관련
http://razorsql.com/docs/help_mysql.html
Database 두개 이상 사용 시 주의사항
'프로그래밍 > Web' 카테고리의 다른 글
게시판 만들기 (0) | 2018.02.18 |
---|---|
Spring과 Cookie & Session (0) | 2018.02.05 |
DAO, DTO, Service (4) | 2018.01.28 |
Annotation과 Bean (2) | 2018.01.27 |
Spring Bean (2) | 2018.01.27 |
- Total
- Today
- Yesterday
- thymeleaf cannot resolve
- Tasklet
- 클로저
- npm
- nodejs
- Bean
- spring batch
- Closure
- mybatis
- @Component
- thymeleaf 변수 인식
- @Autowired
- chunk
- Check point within polygon
- unity
- Linux
- Bin
- @Qualifier
- Barycentric coordinates
- spring
- Express
- MySQL
- JavaScript
- @Bean
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |