Try the operating environment of the java framework with docker.
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
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: 
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.
docker-compose up -d dbserver
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.
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;
docker / .env.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
create table STAFF (
    EMP_ID     number primary key,
    STAFF_NAME varchar2(100)
);
insert into STAFF (EMP_ID, STAFF_NAME) values (1, 'Jasmine');
docker/gradle/Dockerfile
FROM gradle:4.8.1-jdk8
WORKDIR /app
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.
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
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);
	}
}
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
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/にブラウザでアクセスして表示を確認。
[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