본문 바로가기
개발/java,spring,springboot

Spring boot(maven) + oracle db(Oracle 11g express) + lombok CRUD example

by 개발자종혁 2020. 5. 6.
728x90

기존의 oracle driver는 springboot에 제대로 적용하려면 jar파일을 옮기는 귀찮은 작업을 거쳐야 함.

그러나 spring boot 2.2.x 부터 개선되어 dependencies에만 추가해도 사용 가능.

 

 

설정

1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<!-- jpa, crud repository -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

		<!-- 프로젝트 lombok (get,set 을 편리하게 만들수 있는 오픈소스 라이브러리) -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.10</version>
			<scope>provided</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<dependency>
			<groupId>com.oracle.ojdbc</groupId>
			<artifactId>ojdbc8</artifactId>
			<scope>runtime</scope>
		</dependency>
	
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

 

2. src/main/resources/application.properties

spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=false
spring.jpa.show-sql=true


spring.datasource.driver-class-name=com.oracle.ojdbc.Driver
spring.datasource.url=jdbc:oracle:thin:@localhost:49161/xe
spring.datasource.username=system
spring.datasource.password=oracle
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
# spring.datasource.hikari.connectionTimeout=30000
# spring.datasource.hikari.idleTimeout=600000
# spring.datasource.hikari.maxLifetime=1800000

url과 username, password는 자신의 설정에 따라 바꾼다.

 

 

3. src/main/java/com/your/path/datasource/OracledataSource.java

(your/path 부분에는 start intilzr 로 만들었을 경우 DemoApplication.java이 들어있는 폴더까지 경로를 넣으면 된다)

 

package com.your.path.datasource;

import com.zaxxer.hikari.HikariDataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration

public class OracleDatasource {
    @Bean
    @ConfigurationProperties("app.datasource")
    public HikariDataSource hikariDataSource(){
        return DataSourceBuilder
                .create()
                .type(HikariDataSource.class)
                .build();
    }
}

 

 

CRUD 예제

1. 자동 DDL 부분

src/main/resources/db/migration/DDL.sql


CREATE TABLE person(
    id VARCHAR(100) NOT NULL PRIMARY KEY,
    NAME VARCHAR(100) NOT NULL
);

 

2. 테이블 모델 정의 부분

src/main/java/com/your/path/model/Person.java

package com.your.path.model

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Table(name="person")
public class Person {

    @Id
    @Column
    private String id;

    @NotBlank
    private String name;
    

}

 

3. DAO 부분

src/main/java/com/your/path/dao/PersonJpaDao.java

package com.your.path.dao;

import java.util.UUID;

import com.example.demo.model.jpa.Person;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonJpaDao extends JpaRepository<Person, String> {

    default String generateRandomId(){
        return UUID.randomUUID().toString();
    }
}

 

4. REST 부분

src/main/java/com/your/path/dao/PersonJpaDao.java

package com.your.path.api;

import java.util.List;

import javax.validation.Valid;

import com.example.demo.dao.PersonJpaDao;
import com.example.demo.model.jpa.Person;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("api/v2/person")
@RestController
public class PersonJpaController {

    private final PersonJpaDao personDao;

    @Autowired
    public PersonJpaController(PersonJpaDao personDao) {
        this.personDao = personDao;
    }

    @PostMapping
    public void addPerson(@Valid @NonNull @RequestBody Person person) {
        
        person.setId(personDao.generateRandomId());
        personDao.save(person);
    }

    @GetMapping
    public List<Person> getAllPeople() {
        return personDao.findAll();
    }

    @GetMapping(path = "{id}")
    public Person getPersonById(@PathVariable("id") String id) {
        return personDao.findById(id).get();
    }

    @DeleteMapping(path = "{id}")
    public void deletePersonById(@PathVariable("id") String id) {
        personDao.deleteById(id);
    }

    @PutMapping(path = "{id}")
    public void updatePerson(@PathVariable("id") String id, @Valid @NonNull @RequestBody Person personToUpdate) {
        personDao.findById(id).map(person -> {
            person.setId(id);
            person.setName(personToUpdate.getName());
            return personDao.save(person);
        }).orElseGet(() -> {
            
            personToUpdate.setId(id);
            return personDao.save(personToUpdate);
        });
        ;
    }
}

 

728x90

댓글