✍️
이런 걸
배워요!
JPA의 기본기를 탄탄하게 다질 수 있습니다.
JPA의 내부 동작 방식을 이해할 수 있습니다.
객체와 DB 테이블을 올바르게 설계하고 매핑할 수 있습니다.
실무에서 자신있게 JPA를 사용할 수 있습니다.
인프런 강의 : https://www.inflearn.com/course/ORM-JPA-Basic
강의 자료 :
https://github.com/braverokmc79/jpa-basic-lecture-file
소스 :
https://github.com/braverokmc79/jpa-shop
[4] 연관관계 매핑 기초
13. 단방향 연관관계
강의:
https://www.inflearn.com/course/lecture?courseSlug=ORM-JPA-Basic&unitId=21696&tab=curriculum
소스 :
https://github.com/braverokmc79/ex-jpa-13-1
Member
package jpashop.home.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter public class Member { @Id @GeneratedValue private Long id; @Column(name="USERNAME") private String username; @ManyToOne @JoinColumn(name = "TEAM_ID") private Team team; public Member() { } }
Team
package jpashop.home.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter public class Team { @Id @GeneratedValue @Column(name="TEAM_ID") private Long id; private String name; }
JpaMain
package jpashop.home; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import jpashop.home.domain.Member; import jpashop.home.domain.Team; public class JpaMain { public static void main(String[] args) { EntityManagerFactory emf=Persistence.createEntityManagerFactory("hello"); EntityManager em=emf.createEntityManager(); //JPA 의 모든 데이터 변경은 트랜잭션 안에서 실행 되어야 한다. EntityTransaction tx=em.getTransaction(); tx.begin(); try { Team team =new Team(); team.setName("TeamA"); em.persist(team); Member member =new Member(); member.setUsername("member1"); member.setTeam(team); em.persist(member); Team findTeam=member.getTeam(); System.out.println(" findTeam : " + findTeam.getName()); tx.commit(); }catch(Exception e) { tx.rollback(); }finally { em.close(); } emf.close(); } }
14. 단방향 연관관계
강의:
https://www.inflearn.com/course/lecture?courseSlug=ORM-JPA-Basic&unitId=21697&tab=curriculum
소스 :
https://github.com/braverokmc79/ex-jpa-13-1
Team
package jpashop.home.domain; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter public class Team { @Id @GeneratedValue @Column(name="TEAM_ID") private Long id; private String name; /**★★★외래키가 있는 곳을 주인으로 정해라! * 객체와 테이블이 관계를 맺는 차이 * 객체 연관관계 =2개 * mappedBy 는 Many 테이블의 외래키값을 넣으면 된다. * 여기서는 Member 테이블의 team 이 외래키이다. * * 조회만 가능하고 외래키의 값의 업데이트는 member 의 team 에서 업데이트 가능하다. */ @OneToMany(mappedBy = "team") private List<Member> members=new ArrayList(); }
15. 양방향 연관관계와 연관관계의 주인 2 - 주의점, 정리
강의:
https://www.inflearn.com/course/lecture?courseSlug=ORM-JPA-Basic&unitId=21698&tab=curriculum
★ 연관관계의 주인은 외래 키의 위치를 기준으로 정해야함
16. 실전 예제 2 - 연관관계 매핑 시작
강의:
https://www.inflearn.com/course/lecture?courseSlug=ORM-JPA-Basic&unitId=21699&tab=curriculum
Member
package jpashop.home.domain; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import lombok.Getter; import lombok.Setter; @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; //mappedBy 는 연관 관계의 주인은 누구? member @OneToMany(mappedBy = "member") private List<Order> orderList=new ArrayList<>(); }
Order
package jpashop.home.domain; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter @Table(name="ORDERS") //ORDER DB 에서 예약어로 사용되는 경우 많아서 ORDERS public class Order { @Id @GeneratedValue @Column(name="ORDER_ID") private Long id; @ManyToOne @JoinColumn(name="MEMBER_ID") private Member member; @OneToMany(mappedBy = "order") private List<OrderItem> orderItems=new ArrayList<>(); private LocalDateTime orderDate; //ORDINAL 숫자 타입으로 하면 순서가 꼬이므로 무저건 String 한다 @Enumerated(EnumType.STRING) private OrderStatus status; //양방향 연관 관계 설정 public void addOrderItem(OrderItem orderItem) { orderItems.add(orderItem); orderItem.setOrder(this); } }
OrderItem
package jpashop.home.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter public class OrderItem { @Id @GeneratedValue @Column(name="ORDER_ITEM_ID") private Long id; @ManyToOne @JoinColumn(name="ORDER_ID") private Order order; @ManyToOne @JoinColumn(name="ITEM_ID") private Item item; private int oderPrice; private int count; }
Item
package jpashop.home.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter public class Item { @Id @GeneratedValue @Column(name="ITEM_ID") private Long id; private String name; private String price; private int stockQuantity; }
OrderStatus
package jpashop.home.domain; public enum OrderStatus { ORDER, CANCEL }
JpaMain
package jpashop.home; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import jpashop.home.domain.Order; import jpashop.home.domain.OrderItem; public class JpaMain { public static void main(String[] args) { EntityManagerFactory emf=Persistence.createEntityManagerFactory("hello"); EntityManager em=emf.createEntityManager(); //JPA 의 모든 데이터 변경은 트랜잭션 안에서 실행 되어야 한다. EntityTransaction tx=em.getTransaction(); tx.begin(); try { Order order =new Order(); order.addOrderItem(new OrderItem()); tx.commit(); }catch(Exception e) { tx.rollback(); }finally { em.close(); } emf.close(); } }
댓글 ( 4)
댓글 남기기