A note about trying Oracle 11g + Spring boot with Vagrant + Docker compose

things to do

Try the operating environment of the java framework with docker.

Operating environment

Directory structure

project
  + bin   #Shell script for command memorandum
  + data  #docker persistence directory
  - docker
    - gradle
      - Dockerfile
    - oracle
      - 11.2.0.2
        - Checksum.xe
        - Dockerfile.xe
        - checkDBStatus.sh
        - rnOracle.sh
        - setPasword.sh
        - xe.rsp
        - oracle-xe-11.2.0-1.0.x86_64.rpm.zip #Downloaded from Oracle..Ignore with gitignore
      - buildDockerImage.sh
    - spring
      - Dockerfile
    - .env # docker-composer.Environment variable settings used in yml
    - docker-compose.yml
  - src
    - hello #Modified to Hinagata created by spring initializer
      - build.gradle
      - settings.gradle
      - lib
        - ojdbc7.jar  #Downloaded from Oracle..Ignore with gitignore
      - src
        - main
          - java
            - hello
              - hello
                - model
                  - Staff.java
                - repository
                  - StaffRepository.java
                - HelloApplication.java
          - resouces
            - application.yml
        + test

setting file

docker/.env


ORACLE_PWD=MY_DB_PASSWORD
USER_PASS=MY_DB_USER_PASSWORD

docker/docker-compose.yml


version: '3'
services:
  dbserver:
    build:
      context: ./oracle/11.2.0.2/
      dockerfile: Dockerfile.xe
    volumes:
      - ../data/database:/u01/app/oracle/oradata
      - ./oracle/startup:/docker-entrypoint-initdb.d/startup
    ports:
      - 1521:1521
      - 8085:8080
    env_file: .env
    environment:
      - TZ=`ls -la /etc/localtime | cut -d/ -f8-9`
    shm_size: 1g
    restart: unless-stopped

  gradle:
    build: ./gradle
    user: gradle
    volumes:
      - ../src/hello:/app
      - cache1:/home/gradle/.gradle
    links:
      - dbserver
    environment:
      - TZ=`ls -la /etc/localtime | cut -d/ -f8-9`
    command: [echo, "no work"]

  spring:
    build: ./spring
    ports:
        - "8080:8080"
    volumes:
        - ../src/hello:/app
    links:
      - dbserver
    environment:
      - TZ=`ls -la /etc/localtime | cut -d/ -f8-9`
    command: [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app/build/libs/hello-0.0.1-SNAPSHOT.jar"]

volumes:
  cache1: 

Database preparation

The database was set by referring to [Building Oracle database 11g XE with Docker] [* 1]. Copy the 11.2.0.2 directory of oracle / docker-images. In the same directory oracle-xe-11.2.0-1.0.x86_64.rpm.zip Linux version is placed. Also, download the ojdbc7 driver for connecting from java to DB.

What to clone from github

What to download from Oracle

Database startup

docker-compose up -d dbserver

Connection with sqlplus

You cannot connect unless the database is started. Be sure to do it after docker-compose up.

bin/sqlplus.sh


#!/bin/bash

bin_dir=$(cd $(dirname $0) && pwd)
container_name=dbserver

#Environment variable reading
. $bin_dir/../docker/.env

cd $bin_dir/../docker && docker-compose exec $container_name sqlplus sys/$ORACLE_PWD@localhost:1521/XE as sysdba

Run the shell and try to connect.

vagrant@vagrant[master]:/vagrant/tutorial/lesson/spring$ ./bin/sqlplus.sh

If you access it without starting up, the following error will occur.

7df144c6f135        docker_dbserver              "/bin/sh -c 'exec $O…"   19 seconds ago      Up 18 seconds (health: start
ing)   0.0.0.0:1521->1521/tcp, 0.0.0.0:8085->8080/tcp   docker_dbserver_1
WARNING: The JAVA_OPTS variable is not set. Defaulting to a blank string.

SQL*Plus: Release 11.2.0.2.0 Production on Sun Jul 15 15:08:51 2018

Copyright (c) 1982, 2011, Oracle.  All rights reserved.

ERROR:
ORA-12528: TNS:listener: all appropriate instances are blocking new connections

Press Enter twice to exit.

Enter user-name:
ERROR:
ORA-12547: TNS:lost contact


Enter user-name:
ERROR:
ORA-12547: TNS:lost contact


SP2-0157: unable to CONNECT to ORACLE after 3 attempts, exiting SQL*Plus

Try connecting with sqlplus again.

vagrant@vagrant[master]:/vagrant/tutorial/lesson/spring$ ./bin/sqlplus.sh
7df144c6f135        docker_dbserver              "/bin/sh -c 'exec $O…"   25 seconds ago      Up 23 seconds (health: start
ing)   0.0.0.0:1521->1521/tcp, 0.0.0.0:8085->8080/tcp   docker_dbserver_1
WARNING: The JAVA_OPTS variable is not set. Defaulting to a blank string.

SQL*Plus: Release 11.2.0.2.0 Production on Sun Jul 15 15:08:55 2018

Copyright (c) 1982, 2011, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

SQL> 

Is it wrong to launch sqlplus? If anyone knows how to do it well, please let me know.

User preparation

If you can connect with sqlplus, create a user to connect from java. This time, I created a user with all privileges because I will not publish it only for the test to start it.

CREATE TABLESPACE my_data DATAFILE '/u01/app/oracle/oradata/MY_DATA.dbf' SIZE 200M  SEGMENT SPACE MANAGEMENT AUTO;
CREATE USER testuser IDENTIFIED BY "my_pass" DEFAULT TABLESPACE my_data TEMPORARY TABLESPACE temp;
GRANT DBA TO testuser ;
quit;

Once logged out, try to connect with the created user.

bin/sqlplus.sh


#!/bin/bash

bin_dir=$(cd $(dirname $0) && pwd)
container_name=dbserver
. $bin_dir/../docker/.env
cd $bin_dir/../docker && docker-compose exec $container_name sqlplus testuser/$USER_PASS@localhost:1521/XE

Creating a test table

create table STAFF (
    EMP_ID     number primary key,
    STAFF_NAME varchar2(100)
);
insert into STAFF (EMP_ID, STAFF_NAME) values (1, 'Jasmine');

Build tools and sources

Build tool docker file

docker/gradle/Dockerfile


FROM gradle:4.8.1-jdk8
WORKDIR /app

Source preparation

Create a project using Spring Initializer with reference to [Spring Boot starting with Docker] [* 3]. Place it under the src folder. Since I want to connect to the DB this time, I added the settings related to the DB.

setting file

src/hello/build.gradle


buildscript {
	ext {
		springBootVersion = '2.0.3.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'hello'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
	mavenCentral()
}


dependencies {
  compile('org.springframework.boot:spring-boot-starter-web')
  compile('org.springframework.boot:spring-boot-starter-data-jpa')
  compile files('lib/ojdbc7.jar')
  testCompile('org.springframework.boot:spring-boot-starter-test')
}

src/hello/src/main/resouce/applicatin.yaml


spring:
  datasource:
    url: jdbc:oracle:thin:@//dbserver:1521/XE
    username: testuser
    password: pass
    driverClassName: oracle.jdbc.driver.OracleDriver
    testWhileIdle: true
    validationQuery: SELECT 1
  jpa:
    showSql: true
    hibernate:
      ddlAuto: create-drop
      naming:
        implicitStrategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
        physicalStrategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
    properties:
      hibernate:
        dialect: org.hibernate.dialect.Oracle10gDialect

program

src/hello/src/main/java/hello/hello/model/Staff.java


package hello.hello.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;

@Table(name="staff")
@Entity
public class Staff {

  @Id 
  @Column(name="emp_id")
  private long id;

  @Column(name="staff_name")
  private String name;

  public void setId(long id){
    this.id = id;
  }
  public long getId(){
    return this.id;
  }

  public void setName(String  name){
    this.name = name;
  }

  public String getName(){
    return this.name;
  }
}

src/hello/src/main/java/hello/hello/repository/StaffRepository.java


package hello.hello.repository;

import java.util.Optional;
import org.springframework.data.repository.CrudRepository;

import hello.hello.model.Staff;

public interface StaffRepository extends CrudRepository<Staff, Long> {
  Optional<Staff> findById(long id);
}

src/hello/src/main/java/hello/hello/HelloApplication.java


package hello.hello;

import java.util.Optional;
import java.util.Collections;
import java.util.Map;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import hello.hello.model.Staff;
import hello.hello.repository.StaffRepository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@SpringBootApplication
@RestController
public class HelloApplication {
  @Autowired StaffRepository repository;

  @PersistenceContext
  private EntityManager entityManager;

  @RequestMapping("/")
  public String home() {
      return "Hello World from Docker";
  }
  @RequestMapping("/staff")
  public String staff() {
      Optional<Staff> optional =  repository.findById(1);
      Staff staff = optional.orElseGet(() -> new Staff());
      return "Hello " + staff.getName();
  }

  @RequestMapping("/query")
  public String query() {
      List<Staff> results = entityManager
            .createNativeQuery("select * from staff where emp_id = :id ", Staff.class)
            .setParameter("id",1)
            .getResultList();
      String name = "";

      if(results.size() != 0){
        name = results.get(0).getName();
      }
      return "Hello " + name;
  }
	public static void main(String[] args) {
		SpringApplication.run(HelloApplication.class, args);
	}
}

Run build

bin/clean-build.sh


#!/bin/bash

#Get the absolute path of this shell script directory.
bin_dir=$(cd $(dirname $0) && pwd)
container_name=gradle
cd $bin_dir/../docker && docker-compose run $container_name  gradle clean build

Start-up

docker/spring/Dockerfile


FROM openjdk:jdk-alpine
WORKDIR /app
ENV JAVA_OPTS=""

bin/up.sh


#!/bin/bash

#Get the absolute path of this shell script directory.
bin_dir=$(cd $(dirname $0) && pwd)

composeFile=${1:-"docker-compose.yml"}
cd $bin_dir/../docker && docker-compose -f $composeFile up $@

Start with ./bin/up.sh.

http://<仮想環境のIP>:8080/にブラウザでアクセスして表示を確認。

Source at this point

reference

[Building Oracle database 11g XE with Docker] [* 1] [Running Oracle DB 11g with docker] [* 2] [Spring Boot starting with Docker] [* 3] [Tablespace] [* 4] oracle spring sample auto increment [Create a Spring Boot development environment with docker] [* 7] sample [Summary of query implementation method in Spring Data JPA] [* 10] [[Java EE] Introduction to JPA that is still in time] [* 11] [First JPA--Simple and easy to use, learn the basics of Java EE's data persistence function] [* 12] Invalid number format for port number [Gradle usage memo] [* 14] [In Docker-/ etc / localtime: / etc / localtime: ro gives Mount Denied] [* 15] docker-compose [autoincrement with oracle] [* 17]

Recommended Posts

A note about trying Oracle 11g + Spring boot with Vagrant + Docker compose
Create a Spring Boot development environment with docker
Spring Boot starting with Docker
Spring Boot gradle build with Docker
Spring Boot environment construction with Docker (January 2021 version)
Create a website with Spring Boot + Gradle (jdk1.8.x)
Create a web api server with spring boot
Create a docker environment for Oracle 11g XE
A memorandum when trying Spring Data JPA with STS
[JUnit 5 compatible] Write a test using JUnit 5 with Spring boot 2.2, 2.3
Implement a simple Rest API with Spring Security with Spring Boot 2.0
A story about trying to get along with Mockito
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
A memorandum when creating a REST service with Spring Boot
[Note] Create a java environment from scratch with docker
Create a simple demo site with Spring Security with Spring Boot 2.1
I wrote a test with Spring Boot + JUnit 5 now
Database environment construction with Docker in Spring boot (IntellJ)
Download with Spring Boot
Create a Docker image with the Oracle JDK installed (yum
A story packed with the basics of Spring Boot (solved)
Let's make a simple API with EC2 + RDS + Spring boot ①
Implement a simple Rest API with Spring Security & JWT with Spring Boot 2.0
A note about Java GC
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Get started with Spring boot
A note about the scope
Hello World with Spring Boot!
File upload with Spring Boot
Spring Boot starting with copy
A private note about AtomicReference
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Docker × Spring Boot environment construction
Add module with Spring Boot
Getting Started with Spring Boot
[Java] [Spring] Spring Boot 1.4-> 1.2 Downgrade Note
Create microservices with Spring Boot
Send email with spring boot
Let's make a book management web application with Spring Boot part1
[Note] A story about changing Java build tools with VS Code
Let's make a book management web application with Spring Boot part3
Let's make a book management web application with Spring Boot part2
I made a simple search form with Spring Boot + GitHub Search API.
Sample code to unit test a Spring Boot controller with MockMvc
Build a development environment for Django + MySQL + nginx with Docker Compose
Image Spring Boot app using jib-maven-plugin and start it with Docker