Skip to content

Working with MySQL

Somkiat Puisungnoen edited this page Dec 3, 2023 · 3 revisions

Working with MySQL

  • MySQL for production
  • H2 for testing

1. Edit file pom.xml

<!-- For production-->
<dependency>
      <groupId>com.mysql</groupId>
      <artifactId>mysql-connector-j</artifactId>
      <scope>runtime</scope>
</dependency>
<!-- For Testing-->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

2. Configuration database in application

For production :: MySQL

  • File src/main/resources/application.properties
spring.datasource.url=${MYSQL_URL:jdbc:mysql://174.138.26.57:3306/demo_workshop?allowPublicKeyRetrieval=true&useSSL=false}
spring.datasource.username=${MYSQL_USER:user}
spring.datasource.password=${MYSQL_PASS:password}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto = none
spring.jpa.show-sql=true

Start server for testing configuration

$mvnw spring-boot:run

For testing :: H2 database

  • File src/test/resources/application.properties
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update

Run testing and see result

$mvnw clean test

Start MySQL with Docker

docker container run -d --name mysql \
    -e MYSQL_ROOT_PASSWORD=my-secret-pw \
    -e MYSQL_USER=user \
    -e MYSQL_PASSWORD=password \
    -e MYSQL_DATABASE=demo_workshop \
    -p 3306:3306 \
    mysql:8.2.0