イメージをpullします
コンテナの起動
docker pull mysql:5.6
コンテナを起動します。
docker run \ -p 3306:3306 \ --name mysqld \ -e MYSQL_DATABASE=hr \ -e MYSQL_USER=hr \ -e MYSQL_PASSWORD=hr \ -e MYSQL_ROOT_PASSWORD=password \ -d mysql
以下がないとホストからmysqlに接続できないです。
-p 3306:3306 \
以下のオプションで、hrデータベースとhrデータベースに対してもろもろ権限を持ってるhrユーザー(パスワードはhr)を作成しています。
-e MYSQL_DATABASE=hr \ -e MYSQL_USER=hr \ -e MYSQL_PASSWORD=hr \
ホストOSから以下のコマンドを叩けば接続できるはず。
mysql -u hr -h 127.0.0.1 -P 3306 -phr
つながったらついでにテーブルも作っておきます。
CREATE TABLE employee_register_events(
id INT PRIMARY KEY AUTO_INCREMENT ,
first_name VARCHAR(100),
last_name VARCHAR(100),
salary INT
);
アプリケーションの準備
Spring Bootのアプリケーションに以下の依存を追加
// https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter
compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '1.3.1'
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
runtime group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
application.ymlにDBの接続情報を追加
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/hr
username: hr
password: hr
driverClassName: com.mysql.jdbc.Driver
Mapperクラスを作ります(Kotlinを使ってます)
import org.apache.ibatis.annotations.Insert
import org.apache.ibatis.annotations.Mapper
import org.apache.ibatis.annotations.Param
data class EmployeeRegisterEvent(
val firstName: String,
val lastName: String,
val salary: Int
)
@Mapper
interface EmployeeTableMapper {
/**
* Insert register event to register_event table
*
* @param event
*/
@Insert("""
insert into employee_register_events (
first_name
, last_name
, salary
) values (
#{event.firstName}
, #{event.lastName}
, #{event.salary})
""")
fun insert(@Param("event") event: EmployeeRegisterEvent): Int
}
テストコードを書いて実行してみます。
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import spock.lang.Specification
@SpringBootTest
class EmployeeTableMapperTest extends Specification {
@Autowired
private EmployeeTableMapper sut
def "test"() {
expect:
sut.insert(new EmployeeRegisterEvent("shown", "white", 200000))
}
}
テーブルをのぞいて見ると、値が入っていました。
mysql> select * from employee_register_events; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | shown | white | 200000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec)