본문 바로가기
국비 교육/SQL(Oracle)

[자바 - 오라클] JPA 연결 - 2

by 육츠 2024. 2. 13.
Contents 접기

조금 더 유기적인 구조로 바꾸면?

 

- 오라클과 연결하는 파일 따로 생성

package com.kdigital.jpa04.util;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

public class ConnectionManager {
	private static EntityManagerFactory factory;
	
	static {
		factory = Persistence.createEntityManagerFactory("jpastudy");
		// 객체가 생성되자마자 바로 가능해진다.
	}
	
	public static EntityManager getManager(){
		return factory.createEntityManager();
	}
	
	public static void close() {
		factory.close();
	}
	
	
}

 

- Product 에 대한 sql

아까와 다른 점이 있다면 여기서는 기본키를 SEQUENCE 객체를 사용하여 생성 시킨다.

-- JPA-04에서 사용할 객체 DDL

DROP TABLE product;
DROP SEQUENCE product_seq;

CREATE TABLE product(
    prod_id NUMBER PRIMARY KEY -- 일련번호
    , prod_name VARCHAR2(50)
    , season VARCHAR2(100)
    , unit_price NUMBER
);


CREATE SEQUENCE product_seq;

SELECT * FROM product;

 

- Product

prodId 를 따로 만들기 때문에 오버로딩 생성자에는 prodId 를 매개변수로 넣지 않는다.

package com.kdigital.jpa04.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.SequenceGenerator;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@NoArgsConstructor // 기본 생성자
@Setter
@Getter
@ToString
@Entity
public class Product {
	
	@SequenceGenerator(
			name = "product_seq_generator", 
			sequenceName = "product_seq",
			initialValue = 1,
			allocationSize = 1 
			// 중복되어서 생성되지 않도록 만들어줌
	)
	
	@Id
	@Column(name = "prod_id") 
	@GeneratedValue(generator = "product_seq_generator")
	private Long prodId; // 오라클의 시퀀스 객체 이용해서 자동발생
	
	@Column(name = "prod_name")
	private String prodName;
	
	private String season;
	
	@Column(name = "unit_price")
	private int unitPrice;
	
	public Product(String prodName, String season, int unitPrice) {
		super();
		this.prodName = prodName;
		this.season = season;
		this.unitPrice = unitPrice;
	}
	
}

 

- Service

package com.kdigital.jpa04.service;

import com.kdigital.jpa04.entity.Product;

public interface ProductService {
	// insert, updare, delete, selectOne
	public void insert();
	public boolean update();
	public boolean delete();
	public Product selectOne();
}

 

- ServiceImpl

UI는 만들지 않았다.

package com.kdigital.jpa04.service;

import java.util.Scanner;

import com.kdigital.jpa04.entity.Product;
import com.kdigital.jpa04.util.ConnectionManager;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityTransaction;

public class ProductServiceImpl implements ProductService {
	Scanner keyin = new Scanner(System.in);

	public ProductServiceImpl() {
		String choice;
		
		while(true) {
			menu();
			choice = keyin.nextLine();
			switch(choice) {
			case "1" : insert(); break;
			case "2" : selectOne(); break;
			case "3" : update(); break;
			case "4" : delete(); break;
			case "0" :  
				System.out.println("## 프로그램을 종료합니다."); 
				ConnectionManager.close();
				return;
			}
			keyin.nextLine();
		}
	}

	// 메인메뉴
	private void menu() {
		System.out.print(" 1) 입력   2) 조회   3) 수정  4) 삭제  0) 종료 : ");
	}

	@Override
	public void insert() {
		String productName, season;
		int price;

		System.out.print("> 제품명: ");
		productName = keyin.nextLine();
		System.out.print("> 계절: ");
		season = keyin.nextLine();
		System.out.print("> 가격: ");
		price = keyin.nextInt();

		Product product = new Product(productName, season, price);

		EntityManager manager = ConnectionManager.getManager();
		EntityTransaction tx = manager.getTransaction();

		try {
			tx.begin();

			manager.persist(product);

			tx.commit();
			System.out.println("저장완료");
		}catch(Exception e) {
			tx.rollback();
		}finally {
			manager.close();
		}
	}

	@Override
	public boolean update() {

		int productId;
		String productName, season;
		int price;

		System.out.print("> 품목번호: ");
		productId = keyin.nextInt();
		keyin.nextLine();


		EntityManager manager = ConnectionManager.getManager();
		EntityTransaction tx = manager.getTransaction();

		try {
			tx.begin();

			Product product = manager.find(Product.class,productId);
			if(product == null) {
				System.out.println("검색된 제품이 없습니다.");
				return false;
				
			} else {
				System.out.print("> 변경 이름 :");
				productName = keyin.nextLine();
				product.setProdName(productName);

				System.out.print("> 변경 계절 :");
				season = keyin.nextLine();
				product.setSeason(season);

				System.out.print("> 변경 가격 :");
				price = keyin.nextInt();
				product.setUnitPrice(price);
				
				System.out.println("변경 완료");
			}
			tx.commit();

		}catch(Exception e) {
			tx.rollback();
		}finally {
			manager.close();
		}
		return false;
	}

	@Override
	public boolean delete() {
		int productId;

		System.out.print("> 품목번호: ");
		productId = keyin.nextInt();
		
		keyin.nextLine();


		EntityManager manager = ConnectionManager.getManager();
		EntityTransaction tx = manager.getTransaction();

		try {
			tx.begin();

			Product product = manager.find(Product.class,productId);
			
			if(product == null) {
				System.out.println("검색된 제품이 없습니다.");
				return false;
				
			} else {
				manager.remove(product);
				System.out.println("삭제가 완료 되었습니다.");
			}
			tx.commit();

		}catch(Exception e) {
			tx.rollback();
		}finally {
			manager.close();
		}
		return false;
	}

	@Override
	public Product selectOne() {
		int productId;

		System.out.print("> 품목번호: ");
		productId = keyin.nextInt();
		keyin.nextLine();

		EntityManager manager = ConnectionManager.getManager();
		EntityTransaction tx = manager.getTransaction();

		try {
			tx.begin();

			Product product = manager.find(Product.class,productId);
			if(product == null) {
				System.out.println("검색된 제품이 없습니다.");

			} else {
				System.out.println(product);
			}
			tx.commit();

		}catch(Exception e) {
			tx.rollback();
		}finally {
			manager.close();
		}
		return null;
	}
}

 

-  Main

package com.kdigital.jpa04;

import com.kdigital.jpa04.service.ProductServiceImpl;

public class Main {

	public static void main(String[] args) {
		new ProductServiceImpl();
	}

}