SpringBoot + MyBatis + Gradle + MySQL 세팅방법에 대한 페이지입니다.
기본 세팅
build.gradle
dependencies {
...
// MyBatis
compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2")
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('mysql:mysql-connector-java')
...
}
application.yml
spring:
datasource:
url: jdbc:mysql://rds주소:포트명(기본은 3306)/database명
username: db계정
password: db계정 비밀번호
driver-class-name: org.mysql.jdbc.Driver
mybatis:
type-aliases-package: com.example.myproject.mapper
mapper-locations: mybatis/mapper/**/*.xml
resources/mybatis/mybatis-config.xml
mybatis 설정파일
<?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>
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
MySQL 설치
MySQL 로컬 설치 방법은 블로그를 참고해주세요.
: http://0719s.tistory.com/2
MySQL 예제 데이터 생성
$ cd /usr/local/mysql/bin/
$ ./mysql -u root -p
=> 비밀번호 입력 후 mysql 접속mysql> use mysql; // 기본 mysql 을 사용하도록 하겠습니다. (DB 생성 후에 사용하시면됩니다.)mysql> create table employee (
-> id int not null auto_increment,
-> name char(30) not null,
-> primary key (id)
-> );mysql> insert into employee values (1, 'hyuna');
예제 코드 작성
EmployeeController
@Controller
public class EmployeeController {
private EmployeeService employeeService;
@Autowired
EmployeeController(
EmployeeService employeeService
) {
this.employeeService = employeeService;
}
@GetMapping("/employee")
@ResponseBody
public List<Map<String, Object>> getEmployee() {
return employeeService.getEmployee();
}
}
EmployeeService
public interface EmployeeService {
List<Map<String, Object>> getEmployee();
}
EmployeeServiceImplement
@Service
public class EmployeeServiceImplement implements EmployeeService {
private EmployeeMapper employeeMapper;
@Autowired
EmployeeServiceImplement(
EmployeeMapper employeeMapper
) {
this.employeeMapper = employeeMapper;
}
public List<Map<String, Object>> getEmployee() {
return employeeMapper.getEmployee();
}
}
EmployeeMapper
@Repository
@Mapper
public interface EmployeeMapper {
List<Map<String, Object>> getEmployee();
}
resources/mybatis/mapper/EmployeeMapper.xml
<?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.example.myproject.mapper.EmployeeMapper">
<select id="getEmployee" resultType="java.util.HashMap">
SELECT * FROM employee;
</select>
</mapper>
코드 실행 후 localhost:8080/employee 접속하면 employee 데이터를 조회하는 것을 확인할 수 있다.
AWS RDS 세팅
AWS의 RDS 세팅시에는 application.yml 파일에서 DB 설정만 바꿔주면 된다.
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://<AWS RDS 엔드포인트>:3306/<DB_NAME>
username: <username>
password: <password>
platform: mysql