java 스프링부트 ( spring boot ) / JPA 연관관계 ( 2 )

김동명·2022년 12월 8일
0

스프링부트

목록 보기
15/19
  • 다음 그림 구현하기

프로젝트 세팅

  • persistence.xml
<?xml version="1.0" encoding="UTF-8"?>

<persistence version="2.2"
   xmlns="http://xmlns.jcp.org/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
   <persistence-unit name="hello">
      <properties>
         <!-- 필수 속성 -->
         <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
         <property name="javax.persistence.jdbc.user" value="springjpa" />
         <property name="javax.persistence.jdbc.password" value="springjpa" />
         <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:xe" />
         <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<!--          <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL10Dialect" /> -->
		
		 <!-- 테이블 생성 옵션 -->
	     <property name="hibernate.hbm2ddl.auto" value="create"/>
		
         <!-- 옵션 -->
         <!-- 콘솔에 하이버네이트가 실행하는 SQL문 출력 -->
         <property name="hibernate.show_sql" value="true" />
         <!-- SQL 출력 시 보기 쉽게 정렬 -->
         <property name="hibernate.format_sql" value="true" />
         <!-- 쿼리 출력 시 주석(comments)도 함께 출력 -->
         <property name="hibernate.use_sql_comments" value="true" />
      </properties>
   </persistence-unit>
</persistence>

시작


jpaitem.domain 패키지 생성

  • jpaitem.domain 패키지 > Item.java 생성
@Entity
@Getter @Setter
public class Item {
	
	@Id @GeneratedValue // 전략을 특정해주지 않으면 자동으로 생성 시퀀스를 생성한다.
    @Column(name = "ITEM_ID")
	private Long id;
	private String name;
	private int price;
	private int stockQuantity;
    
}

  • jpaitem.domain 패키지 > Member.java 생성
@Entity
@Getter @Setter
public class Member {

	@Id @GeneratedValue
	@Column(name = "MEMBER_ID")
	private Long id;
	private String name;
	private String city;
	private String street;
	private String zipcode;
	
}

  • jpaitem.domain 패키지 > Order.java 생성
@Entity
@Table(name = "ORDERS")
@Getter @Setter
public class Order {
	
	@Id @GeneratedValue
	@Column(name = "ORDER_ID")
	private Long id;
	@Column(name = "MEMBER_ID")
	private Long memberId;
	private LocalDateTime orderDate;
	private String status;
}

  • jpaitem.domain 패키지 > OrderItem.java 생성
@Entity
@Getter @Setter
public class OrderItem {

	@Id @GeneratedValue
	@Column(name = "ORDER_ITEM_ID")
	private Long id;
	@Column(name = "ORDER_ID")
	private Long orderId;
	@Column(name = "ITEM_ID")
	private Long itemId;
	private int orderPrice;
	private int count;
}

  • jpaitem 패키지 > JpaMain.java 생성
public class JpaMain {

	public static void main(String[] args) {
		
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
		EntityManager em = emf.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		
		try {
			
			
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
		} finally {
			em.close();
			emf.close();
		}
		
		
		
		
	}
	
}

  • 결과 ( JpaMain.java 실행 시 )



1. Member - Order 양방향 매핑

  • Order.java 수정
@Entity
@Table(name = "ORDERS")
@Getter @Setter
public class Order {
	
	@Id @GeneratedValue
	@Column(name = "ORDER_ID")
	private Long id;
//	@Column(name = "MEMBER_ID")
//	private Long memberId;
	private LocalDateTime orderDate;
	private String status;
	
	@ManyToOne
	@JoinColumn(name = "MEMBER_ID")
	private Member member;
}

  • Member.java 수정
@Entity
@Getter @Setter
public class Member {

	@Id @GeneratedValue
	@Column(name = "MEMBER_ID")
	private Long id;
	private String name;
	private String city;
	private String street;
	private String zipcode;
	
	@OneToMany(mappedBy = "member")
	private List<Order> order = new ArrayList<Order>();
	
	public void addOrder(Order order) {
		order.setMember(this);
		this.order.add(order);
	}
}



2. OrderItem - Order/Item 양방향 매핑

  • OrderItem.java 수정
@Entity
@Getter @Setter
public class OrderItem {

	@Id @GeneratedValue
	@Column(name = "ORDER_ITEM_ID")
	private Long id;
//	@Column(name = "ORDER_ID")
//	private Long orderId;
//	@Column(name = "ITEM_ID")
//	private Long itemId;
	private int orderPrice;
	private int count;
	
	@ManyToOne
	@JoinColumn(name = "ORDER_ID")
	private Order order;
	
	@ManyToOne
	@JoinColumn(name = "ITEM_ID")
	private Item item;
	
}

  • Order.java 수정
...
	@OneToMany(mappedBy= "order")
	private List<OrderItem> orderItem = new ArrayList<OrderItem>();
	
	public void addOrderItem(OrderItem orderItem) {
		orderItem.setOrder(this);
		this.orderItem.add(orderItem);
	}
}

  • Item.java
...
	@OneToMany(mappedBy = "item")
	private List<OrderItem> orderItem = new ArrayList<OrderItem>();
	
	public void addOrderItem(OrderItem orderItem) {
		orderItem.setItem(this);
		this.orderItem.add(orderItem);
	}
	
	
}

  • JpaMain.java
public class JpaMain {

	public static void main(String[] args) {
		
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
		EntityManager em = emf.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		
		try {
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
		} finally {
			em.close();
			emf.close();
		}
		
	}
	
}

  • 결과
profile
코딩공부

0개의 댓글