프로그래밍n학습자료(2018~)/Hibernate

[Hibernate] 6. Hibernate(하이버네이트) 테이블 관계 - Many To Many

단세포소년 2018. 3. 8. 16:58
반응형

ManyToMany

 

 

People club 관계이다.

 

people 여러 club 가입가능하고 club 여러 people 가입 받을 있다.

 

 

 

 

CREATE TABLE `people` (

  `PEOPLE_ID` int(11) NOT NULL AUTO_INCREMENT,

  `PEOPLE_NAME` varchar(45) NOT NULL,

  PRIMARY KEY (`PEOPLE_ID`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

CREATE TABLE `club` (

  `CLUB_ID` int(11) NOT NULL AUTO_INCREMENT,

  `CLUB_NAME` varchar(45) NOT NULL,

  PRIMARY KEY (`CLUB_ID`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

CREATE TABLE `people_club` (

  `PC_PEOPLE_ID` int(11) NOT NULL,

  `PC_CLUB_ID` int(11) NOT NULL,

  PRIMARY KEY (`PC_PEOPLE_ID`,`PC_CLUB_ID`),

  KEY `fk_people_club_club_idx` (`PC_CLUB_ID`),

  CONSTRAINT `fk_people_club_club` FOREIGN KEY (`PC_CLUB_ID`) REFERENCES `club` (`CLUB_ID`) ON DELETE CASCADE ON UPDATE CASCADE,

  CONSTRAINT `fk_people_club_people` FOREIGN KEY (`PC_PEOPLE_ID`) REFERENCES `people` (`PEOPLE_ID`) ON DELETE CASCADE ON UPDATE CASCADE

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 


 

 

 

 

 

ManyToMany(Bidirectional(양방향))

 

맵핑

관계 테이블(people_club) 경우는 따로 접근하지 않을 경우는  맵핑하지 않아도 된다.

 

People

package org.onecellboy.db.hibernate.table;

 

import java.util.LinkedList;

import java.util.List;

 

import javax.persistence.Basic;

import javax.persistence.CascadeType;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.ManyToMany;

import javax.persistence.OneToMany;

import javax.persistence.OneToOne;

import javax.persistence.PrimaryKeyJoinColumn;

import javax.persistence.Table;

 

@Entity

@Table(name="people")

public class People_Bi {

 

        @Id

        @GeneratedValue(strategy=GenerationType.IDENTITY)

        @Column(name="PEOPLE_ID",columnDefinition="INT")

        private int id;

        

        @Column(name="PEOPLE_NAME",columnDefinition="VARCHAR(45)")

        private String name;

 

        

                

        @OneToMany(fetch=FetchType.LAZY,mappedBy="people", cascade = CascadeType.ALL,orphanRemoval=true)

        private List<Car_Bi> cars = new LinkedList<Car_Bi>();

        

        

        @ManyToMany(fetch=FetchType.LAZY,mappedBy="peoples", cascade = CascadeType.ALL)

        private List<Club_Bi> clubs = new LinkedList<Club_Bi>();

        

        

        

        

        

        public List<Club_Bi> getClubs() {

                return clubs;

        }

 

        public void setClubs(List<Club_Bi> clubs) {

                this.clubs = clubs;

        }

 

        

        public int getId() {

                return id;

        }

 

        public void setId(int id) {

                this.id = id;

        }

 

        public String getName() {

                return name;

        }

 

        public void setName(String name) {

                this.name = name;

        }

        

        

        

        

}

 

설명

@ManyToMany(fetch=FetchType.LAZY,mappedBy="peoples", cascade = CascadeType.ALL)

private List<Club_Bi> clubs = new LinkedList<Club_Bi>();

fetch=FetchType.LAZY : Lazy Loading 하겠다는 것이다.


mappedBy="peoples" : Club_Bi 맵핑클래스의 peoples 멤버변수 관계로 연결되어 있다. ( Club_Bi 클래스에 존재하는 peoples 멤버변수명이다.)

 

 

 

 

 

 

club

package org.onecellboy.db.hibernate.table;

 

import java.util.LinkedList;

import java.util.List;

 

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.FetchType;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.JoinColumn;

import javax.persistence.JoinTable;

import javax.persistence.ManyToMany;

import javax.persistence.ManyToOne;

import javax.persistence.Table;

 

@Entity

@Table(name="club")

public class Club_Bi {

        

 

        @Id

        @GeneratedValue(strategy=GenerationType.IDENTITY)

        @Column(name="CLUB_ID",columnDefinition="INT")

        private int id;

        

 

        @Column(name="CLUB_NAME",columnDefinition="VARCHAR(45)")

        private String name;

        

        

        @ManyToMany(fetch=FetchType.LAZY /*, cascade = CascadeType.ALL*/)

        @JoinTable(

                        name="people_club",

                        joinColumns= {@JoinColumn(name="PC_CLUB_ID",referencedColumnName="CLUB_ID")},

                        inverseJoinColumns= { @JoinColumn(name="PC_PEOPLE_ID",referencedColumnName="PEOPLE_ID")}

                        )

        private List<People_Bi> peoples = new LinkedList<People_Bi>() ;

 

 

        public int getId() {

                return id;

        }

 

 

        public void setId(int id) {

                this.id = id;

        }

 

 

        public String getName() {

                return name;

        }

 

 

        public void setName(String name) {

                this.name = name;

        }

 

 

        public List<People_Bi> getPeoples() {

                return peoples;

        }

 

 

        public void setPeoples(List<People_Bi> peoples) {

                this.peoples = peoples;

        }

        

 

}

 

 

설명

@ManyToMany(fetch=FetchType.LAZY /*, cascade = CascadeType.ALL*/)

        @JoinTable(

                        name="people_club",

                        joinColumns= {@JoinColumn(name="PC_CLUB_ID",referencedColumnName="CLUB_ID")},

                        inverseJoinColumns= { @JoinColumn(name="PC_PEOPLE_ID",referencedColumnName="PEOPLE_ID")}

                        )

@ManyToOne : 다대일 관계라는 것이다.

@JoinTable : 관계 테이블로 조인되었다는 .
name :
관계 테이블명이다.
joinColumns : 조인 컬럼명 집합이다. 조인이 컬럼이 아닌 다수의 컬럼으로도 관계 있기 때문에 여러 JoinColumn 입력가능하다.


@JoinColumn(name="PC_CLUB_ID",referencedColumnName="CLUB_ID") : name 관계(Join) 테이블의 컬럼명이다. referencedColumnName 자신의 컬럼명이다. referencedColumnName 선언하지 않으면 디폴트로 Primary Key이다.  잠시 관계에 대해 생각해보자. 관계테이블(people_club) club 테이블을 참조한다. name( "PC_CLUB_ID") referencedColumnName("CLUB_ID") 참조한다. 라고 해석하라 했다.

 

inverseJoinColumns= { @JoinColumn(name="PC_PEOPLE_ID",referencedColumnName="PEOPLE_ID") : 관계(join) 테이블에서 반대 관계를 뜻한다. people 테이블과 people_club 테이블과의 관계이다. 여기도 마찬가지로 people_club 테이블이 people 테이블을 참조한다. name people_club 컬럼명, referencedColumnName people 테이블의 컬럼명이다.

 

 

 

 

테스트

테스트 코드

package org.onecellboy.db.hibernate;

 

import static org.junit.Assert.*;

 

import java.io.File;

 

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.boot.MetadataSources;

import org.hibernate.boot.registry.StandardServiceRegistry;

import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import org.junit.After;

import org.junit.AfterClass;

import org.junit.BeforeClass;

import org.junit.Test;

import org.onecellboy.db.hibernate.table.Club_Bi;

import org.onecellboy.db.hibernate.table.People_Bi;

 

public class ManyToManyBi {

 

        

        static SessionFactory sessionFactory = null;

        static StandardServiceRegistry registry = null;

 

        static int select_id = 0;

        

        

        @BeforeClass

        public static void setUp()

        {

                registry = new StandardServiceRegistryBuilder().configure(new File("./conf/hibernate/hibernate.cfg.xml"))

                                .build();

                                sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();

 

        }

        

        @AfterClass

        public static void setDown()

        {

                sessionFactory.close();

        }

        

        @After

        public void testAfter()

        {

                System.out.println();

                System.out.println();

        }

        

        @Test

        public void test() {

                

                int temp_id1= -1;

                int temp_id2= -1;

                int temp_id3= -1;

                

                

                Session session =null;

                Transaction tx = null;

                

                System.out.println("======Insert TEST======");

                System.out.println("======1. People1 club들 추가, club들은 people1을 추가하지 않음 ( 한방향에서만 관계생성 ) ======");

                System.out.println("======2. People2, people3 club들 추가, club들은 people2을 추가 ( 양방향에서 관계생성 ) ======");

        

                session = sessionFactory.openSession();

                tx = session.beginTransaction();

                

                People_Bi people1 = new People_Bi();

                people1.setName("sun 1");

                

                People_Bi people2 = new People_Bi();

                people2.setName("sun 2");

                

                People_Bi people3 = new People_Bi();

                people3.setName("sun 3");

                

                

                Club_Bi club1 = new Club_Bi();

                club1.setName("soccer");

                

                Club_Bi club2 = new Club_Bi();

                club2.setName("soccer");

                

                

                

                people1.getClubs().add(club1);

                people1.getClubs().add(club2);

 

 

                people2.getClubs().add(club1);

                people2.getClubs().add(club2);

                club1.getPeoples().add(people2);

                club2.getPeoples().add(people2);

                

 

                people3.getClubs().add(club1);

                people3.getClubs().add(club2);

                club1.getPeoples().add(people3);

                club2.getPeoples().add(people3);

                

                session.save(people1);

                session.save(people2);

                session.save(people3);

                

                

                temp_id1 = people1.getId();

                temp_id2 = people2.getId();

                temp_id3 = people3.getId();

                

                

                

                tx.commit();

                session.close();

                

                

                System.out.println();

                System.out.println("====== people1 people2 club 과의 관계 확인 ======");

                session = sessionFactory.openSession();

                tx = session.beginTransaction();

                

                people1 = session.get(People_Bi.class, temp_id1);

                people2 = session.get(People_Bi.class, temp_id2);

                

                // people1 club 과의 관계가 없다. 양방향 관계인데 양방향에서 관계를 설정하지 않았지 때문..

                System.out.println("people1 club size = "+ people1.getClubs().size());

                

                // people2 club 과의 관계가 존재한다. 양방향에서 관계를 설정하였기 때문이다.

                System.out.println("people2 club size = "+ people2.getClubs().size());

                

                

                tx.commit();

                session.close();

                

                

                System.out.println();

                System.out.println();

                System.out.println("====== people club 의 관계 제거 ======");

                System.out.println("people2에서 club1의 관계를 제거할 경우");

                

                session = sessionFactory.openSession();

                tx = session.beginTransaction();

                

        

                people2 = session.get(People_Bi.class, temp_id2);

                Club_Bi remove = people2.getClubs().remove(0);

                remove.getPeoples().remove(people2);

 

                // 양방향이므로 서로가 서로를 양방향에서 관계를 제거해야한다.

                session.saveOrUpdate(people2);

                

 

                tx.commit();

                session.close();

                

                

                System.out.println();

                System.out.println();

                System.out.println("====== people 제거 ======");

                System.out.println("people2삭제시 people3는 어찌되는가?");

                

                session = sessionFactory.openSession();

                tx = session.beginTransaction();

                

                people3 = session.get(People_Bi.class, temp_id3);

                System.out.println("people2삭제전 people3 club 갯수 = "+people3.getClubs().size());

                

                tx.commit();

                session.close();

                

                

                

                session = sessionFactory.openSession();

                tx = session.beginTransaction();

                

                people2 = session.get(People_Bi.class, temp_id2);

                session.delete(people2);

                

                tx.commit();

                session.close();

                

                

                session = sessionFactory.openSession();

                tx = session.beginTransaction();

                

                people3 = session.get(People_Bi.class, temp_id3);

                System.out.println("people2삭제후 people3 club 갯수 = "+people3.getClubs().size());

                

                tx.commit();

                session.close();

                

                

        }

 

}

 

 

 

 

결과

======Insert TEST======

======1. People1 club들 추가, club들은 people1을 추가하지 않음 ( 한방향에서만 관계생성 ) ======

======2. People2, people3 club들 추가, club들은 people2을 추가 ( 양방향에서 관계생성 ) ======

Hibernate: insert into people (PEOPLE_NAME) values (?)

Hibernate: insert into club (CLUB_NAME) values (?)

Hibernate: insert into club (CLUB_NAME) values (?)

Hibernate: insert into people (PEOPLE_NAME) values (?)

Hibernate: insert into people (PEOPLE_NAME) values (?)

Hibernate: insert into people_club (PC_CLUB_ID, PC_PEOPLE_ID) values (?, ?)

Hibernate: insert into people_club (PC_CLUB_ID, PC_PEOPLE_ID) values (?, ?)

Hibernate: insert into people_club (PC_CLUB_ID, PC_PEOPLE_ID) values (?, ?)

Hibernate: insert into people_club (PC_CLUB_ID, PC_PEOPLE_ID) values (?, ?)

 

====== people1 people2 club 과의 관계 확인 ======

Hibernate: select people_bi0_.PEOPLE_ID as PEOPLE_I1_2_0_, people_bi0_.PEOPLE_NAME as PEOPLE_N2_2_0_ from people people_bi0_ where people_bi0_.PEOPLE_ID=?

Hibernate: select people_inf0_.PEOPLE_INFO_ID as PEOPLE_I1_5_0_, people_inf0_.PEOPLE_INFO_AGE as PEOPLE_I2_5_0_, people_inf0_.PEOPLE_INFO_BIRTHDAY as PEOPLE_I3_5_0_ from people_info people_inf0_ where people_inf0_.PEOPLE_INFO_ID=?

Hibernate: select people_bi0_.PEOPLE_ID as PEOPLE_I1_2_0_, people_bi0_.PEOPLE_NAME as PEOPLE_N2_2_0_ from people people_bi0_ where people_bi0_.PEOPLE_ID=?

Hibernate: select people_inf0_.PEOPLE_INFO_ID as PEOPLE_I1_5_0_, people_inf0_.PEOPLE_INFO_AGE as PEOPLE_I2_5_0_, people_inf0_.PEOPLE_INFO_BIRTHDAY as PEOPLE_I3_5_0_ from people_info people_inf0_ where people_inf0_.PEOPLE_INFO_ID=?

Hibernate: select clubs0_.PC_PEOPLE_ID as PC_PEOPL2_4_0_, clubs0_.PC_CLUB_ID as PC_CLUB_1_4_0_, club_bi1_.CLUB_ID as CLUB_ID1_1_1_, club_bi1_.CLUB_NAME as CLUB_NAM2_1_1_ from people_club clubs0_ inner join club club_bi1_ on clubs0_.PC_CLUB_ID=club_bi1_.CLUB_ID where clubs0_.PC_PEOPLE_ID=?

people1 club size = 0

Hibernate: select clubs0_.PC_PEOPLE_ID as PC_PEOPL2_4_0_, clubs0_.PC_CLUB_ID as PC_CLUB_1_4_0_, club_bi1_.CLUB_ID as CLUB_ID1_1_1_, club_bi1_.CLUB_NAME as CLUB_NAM2_1_1_ from people_club clubs0_ inner join club club_bi1_ on clubs0_.PC_CLUB_ID=club_bi1_.CLUB_ID where clubs0_.PC_PEOPLE_ID=?

people2 club size = 2

 

 

====== people club 의 관계 제거 ======

people2에서 club1의 관계를 제거할 경우

Hibernate: select people_bi0_.PEOPLE_ID as PEOPLE_I1_2_0_, people_bi0_.PEOPLE_NAME as PEOPLE_N2_2_0_ from people people_bi0_ where people_bi0_.PEOPLE_ID=?

Hibernate: select people_inf0_.PEOPLE_INFO_ID as PEOPLE_I1_5_0_, people_inf0_.PEOPLE_INFO_AGE as PEOPLE_I2_5_0_, people_inf0_.PEOPLE_INFO_BIRTHDAY as PEOPLE_I3_5_0_ from people_info people_inf0_ where people_inf0_.PEOPLE_INFO_ID=?

Hibernate: select clubs0_.PC_PEOPLE_ID as PC_PEOPL2_4_0_, clubs0_.PC_CLUB_ID as PC_CLUB_1_4_0_, club_bi1_.CLUB_ID as CLUB_ID1_1_1_, club_bi1_.CLUB_NAME as CLUB_NAM2_1_1_ from people_club clubs0_ inner join club club_bi1_ on clubs0_.PC_CLUB_ID=club_bi1_.CLUB_ID where clubs0_.PC_PEOPLE_ID=?

Hibernate: select peoples0_.PC_CLUB_ID as PC_CLUB_1_4_0_, peoples0_.PC_PEOPLE_ID as PC_PEOPL2_4_0_, people_bi1_.PEOPLE_ID as PEOPLE_I1_2_1_, people_bi1_.PEOPLE_NAME as PEOPLE_N2_2_1_ from people_club peoples0_ inner join people people_bi1_ on peoples0_.PC_PEOPLE_ID=people_bi1_.PEOPLE_ID where peoples0_.PC_CLUB_ID=?

Hibernate: select people_inf0_.PEOPLE_INFO_ID as PEOPLE_I1_5_0_, people_inf0_.PEOPLE_INFO_AGE as PEOPLE_I2_5_0_, people_inf0_.PEOPLE_INFO_BIRTHDAY as PEOPLE_I3_5_0_ from people_info people_inf0_ where people_inf0_.PEOPLE_INFO_ID=?

Hibernate: delete from people_club where PC_CLUB_ID=?

Hibernate: insert into people_club (PC_CLUB_ID, PC_PEOPLE_ID) values (?, ?)

 

 

====== people 제거 ======

people2삭제시 people3는 어찌되는가?

Hibernate: select people_bi0_.PEOPLE_ID as PEOPLE_I1_2_0_, people_bi0_.PEOPLE_NAME as PEOPLE_N2_2_0_ from people people_bi0_ where people_bi0_.PEOPLE_ID=?

Hibernate: select people_inf0_.PEOPLE_INFO_ID as PEOPLE_I1_5_0_, people_inf0_.PEOPLE_INFO_AGE as PEOPLE_I2_5_0_, people_inf0_.PEOPLE_INFO_BIRTHDAY as PEOPLE_I3_5_0_ from people_info people_inf0_ where people_inf0_.PEOPLE_INFO_ID=?

Hibernate: select clubs0_.PC_PEOPLE_ID as PC_PEOPL2_4_0_, clubs0_.PC_CLUB_ID as PC_CLUB_1_4_0_, club_bi1_.CLUB_ID as CLUB_ID1_1_1_, club_bi1_.CLUB_NAME as CLUB_NAM2_1_1_ from people_club clubs0_ inner join club club_bi1_ on clubs0_.PC_CLUB_ID=club_bi1_.CLUB_ID where clubs0_.PC_PEOPLE_ID=?

people2삭제전 people3 club 갯수 = 2

Hibernate: select people_bi0_.PEOPLE_ID as PEOPLE_I1_2_0_, people_bi0_.PEOPLE_NAME as PEOPLE_N2_2_0_ from people people_bi0_ where people_bi0_.PEOPLE_ID=?

Hibernate: select people_inf0_.PEOPLE_INFO_ID as PEOPLE_I1_5_0_, people_inf0_.PEOPLE_INFO_AGE as PEOPLE_I2_5_0_, people_inf0_.PEOPLE_INFO_BIRTHDAY as PEOPLE_I3_5_0_ from people_info people_inf0_ where people_inf0_.PEOPLE_INFO_ID=?

Hibernate: select cars0_.PC_PEOPLE_ID as PC_PEOPL2_3_0_, cars0_.PC_CAR_ID as PC_CAR_I1_3_0_, car_bi1_.CAR_ID as CAR_ID1_0_1_, car_bi1_.CAR_NAME as CAR_NAME2_0_1_, car_bi1_1_.PC_PEOPLE_ID as PC_PEOPL2_3_1_ from people_car cars0_ inner join car car_bi1_ on cars0_.PC_CAR_ID=car_bi1_.CAR_ID left outer join DB_TEST.people_car car_bi1_1_ on car_bi1_.CAR_ID=car_bi1_1_.PC_CAR_ID where cars0_.PC_PEOPLE_ID=?

Hibernate: select clubs0_.PC_PEOPLE_ID as PC_PEOPL2_4_0_, clubs0_.PC_CLUB_ID as PC_CLUB_1_4_0_, club_bi1_.CLUB_ID as CLUB_ID1_1_1_, club_bi1_.CLUB_NAME as CLUB_NAM2_1_1_ from people_club clubs0_ inner join club club_bi1_ on clubs0_.PC_CLUB_ID=club_bi1_.CLUB_ID where clubs0_.PC_PEOPLE_ID=?

Hibernate: select phones0_.PHONE_OWNER_ID as PHONE_OW3_6_0_, phones0_.PHONE_ID as PHONE_ID1_6_0_, phones0_.PHONE_ID as PHONE_ID1_6_1_, phones0_.PHONE_NUMBER as PHONE_NU2_6_1_, phones0_.PHONE_OWNER_ID as PHONE_OW3_6_1_ from phone phones0_ where phones0_.PHONE_OWNER_ID=?

Hibernate: delete from people_club where PC_CLUB_ID=?

Hibernate: delete from club where CLUB_ID=?

Hibernate: delete from people where PEOPLE_ID=?

Hibernate: select people_bi0_.PEOPLE_ID as PEOPLE_I1_2_0_, people_bi0_.PEOPLE_NAME as PEOPLE_N2_2_0_ from people people_bi0_ where people_bi0_.PEOPLE_ID=?

Hibernate: select people_inf0_.PEOPLE_INFO_ID as PEOPLE_I1_5_0_, people_inf0_.PEOPLE_INFO_AGE as PEOPLE_I2_5_0_, people_inf0_.PEOPLE_INFO_BIRTHDAY as PEOPLE_I3_5_0_ from people_info people_inf0_ where people_inf0_.PEOPLE_INFO_ID=?

Hibernate: select clubs0_.PC_PEOPLE_ID as PC_PEOPL2_4_0_, clubs0_.PC_CLUB_ID as PC_CLUB_1_4_0_, club_bi1_.CLUB_ID as CLUB_ID1_1_1_, club_bi1_.CLUB_NAME as CLUB_NAM2_1_1_ from people_club clubs0_ inner join club club_bi1_ on clubs0_.PC_CLUB_ID=club_bi1_.CLUB_ID where clubs0_.PC_PEOPLE_ID=?

people2삭제후 people3 club 갯수 = 1

 

 

 

 

설명

테스트코드

                people1.getClubs().add(club1);

                people1.getClubs().add(club2);

 

 

                people2.getClubs().add(club1);

                people2.getClubs().add(club2);

                club1.getPeoples().add(people2);

                club2.getPeoples().add(people2);

                

 

                people3.getClubs().add(club1);

                people3.getClubs().add(club2);

                club1.getPeoples().add(people3);

                club2.getPeoples().add(people3);

                

                session.save(people1);

                session.save(people2);

                session.save(people3);

 

 

        people1 = session.get(People_Bi.class, temp_id1);

             people2 = session.get(People_Bi.class, temp_id2);

 

        // people1 club 과의 관계가 없다. 양방향 관계인데 양방향에서 관계를 설정하지 않았지 때문..

        System.out.println("people1 club size = "+ people1.getClubs().size());

                

        // people2 club 과의 관계가 존재한다. 양방향에서 관계를 설정하였기 때문이다.

        System.out.println("people2 club size = "+ people2.getClubs().size());

 

 

결과

Hibernate: insert into people (PEOPLE_NAME) values (?)

Hibernate: insert into club (CLUB_NAME) values (?)

Hibernate: insert into club (CLUB_NAME) values (?)

Hibernate: insert into people (PEOPLE_NAME) values (?)

Hibernate: insert into people (PEOPLE_NAME) values (?)

Hibernate: insert into people_club (PC_CLUB_ID, PC_PEOPLE_ID) values (?, ?)

Hibernate: insert into people_club (PC_CLUB_ID, PC_PEOPLE_ID) values (?, ?)

Hibernate: insert into people_club (PC_CLUB_ID, PC_PEOPLE_ID) values (?, ?)

Hibernate: insert into people_club (PC_CLUB_ID, PC_PEOPLE_ID) values (?, ?)

 

Hibernate: select clubs0_.PC_PEOPLE_ID as PC_PEOPL2_4_0_, clubs0_.PC_CLUB_ID as PC_CLUB_1_4_0_, club_bi1_.CLUB_ID as CLUB_ID1_1_1_, club_bi1_.CLUB_NAME as CLUB_NAM2_1_1_ from people_club clubs0_ inner join club club_bi1_ on clubs0_.PC_CLUB_ID=club_bi1_.CLUB_ID where clubs0_.PC_PEOPLE_ID=?

people1 club size = 0

Hibernate: select clubs0_.PC_PEOPLE_ID as PC_PEOPL2_4_0_, clubs0_.PC_CLUB_ID as PC_CLUB_1_4_0_, club_bi1_.CLUB_ID as CLUB_ID1_1_1_, club_bi1_.CLUB_NAME as CLUB_NAM2_1_1_ from people_club clubs0_ inner join club club_bi1_ on clubs0_.PC_CLUB_ID=club_bi1_.CLUB_ID where clubs0_.PC_PEOPLE_ID=?

people2 club size = 2

 

설명

people1 에서 club 과의 관계는  people1 한쪽만 설정했다. 결과 people1 관계된 club insert 되었으나 관계인 people_club 에는 관계가 insert 되지 않았다. people1 관계된 club 없었다.

people2
club 과의 관계가 서로간 양방향으로 설정되었다. 동일한 club 들은 people1 insert될때 같이 insert되어 중복으로 club insert 되지 않았다. 서로간 양방향으로 관계를 설정했으므로 people_club people1 club들의 관계가 insert되었다.

양방향관계는 관계된 객체들이 양방향으로 관계를 설정해야만 한다.

 

 

 

테스트코드

 

people2 = session.get(People_Bi.class, temp_id2);

                Club_Bi remove = people2.getClubs().remove(0);

                remove.getPeoples().remove(people2);

 

                // 양방향이므로 서로가 서로를 양방향에서 관계를 제거해야한다.

                session.saveOrUpdate(people2);

                

 

                

                people3 = session.get(People_Bi.class, temp_id3);

                System.out.println("people2삭제전 people3 club 갯수 = "+people3.getClubs().size());

 

결과

Hibernate: delete from people_club where PC_CLUB_ID=?

Hibernate: insert into people_club (PC_CLUB_ID, PC_PEOPLE_ID) values (?, ?)

 

 

====== people 제거 ======

people2삭제시 people3는 어찌되는가?

Hibernate: select people_bi0_.PEOPLE_ID as PEOPLE_I1_2_0_, people_bi0_.PEOPLE_NAME as PEOPLE_N2_2_0_ from people people_bi0_ where people_bi0_.PEOPLE_ID=?

Hibernate: select people_inf0_.PEOPLE_INFO_ID as PEOPLE_I1_5_0_, people_inf0_.PEOPLE_INFO_AGE as PEOPLE_I2_5_0_, people_inf0_.PEOPLE_INFO_BIRTHDAY as PEOPLE_I3_5_0_ from people_info people_inf0_ where people_inf0_.PEOPLE_INFO_ID=?

Hibernate: select clubs0_.PC_PEOPLE_ID as PC_PEOPL2_4_0_, clubs0_.PC_CLUB_ID as PC_CLUB_1_4_0_, club_bi1_.CLUB_ID as CLUB_ID1_1_1_, club_bi1_.CLUB_NAME as CLUB_NAM2_1_1_ from people_club clubs0_ inner join club club_bi1_ on clubs0_.PC_CLUB_ID=club_bi1_.CLUB_ID where clubs0_.PC_PEOPLE_ID=?

people2삭제전 people3 club 갯수 = 2

설명

people club 관계가 양방향 관계이므로 관계를 없애는 것도 양방향으로 이루어져야 한다.

주의 : 만약 한방향에서만 관계를 없앤다면 관계는 삭제되지 않는다. 양방향으로 서로간 관계를 제거해야한다.

 

 

 

테스트코드

 

people3 = session.get(People_Bi.class, temp_id3);

                System.out.println("people2삭제전 people3 club 갯수 = "+people3.getClubs().size());

                

                tx.commit();

                session.close();

                

                

                

                session = sessionFactory.openSession();

                tx = session.beginTransaction();

                

                people2 = session.get(People_Bi.class, temp_id2);

                session.delete(people2);

                

                tx.commit();

                session.close();

                

                

                session = sessionFactory.openSession();

                tx = session.beginTransaction();

                

                people3 = session.get(People_Bi.class, temp_id3);

                System.out.println("people2삭제후 people3 club 갯수 = "+people3.getClubs().size());

 

결과

people2삭제전 people3 club 갯수 = 2

 

 

 

Hibernate: delete from people_club where PC_CLUB_ID=?

Hibernate: delete from club where CLUB_ID=?

Hibernate: delete from people where PEOPLE_ID=?

 

 

 

 

 

people2삭제후 people3 club 갯수 = 1

설명

people2 people3 같은 하나의 club 관계되어 있다. CascadeType.ALL 옵션 때문에 people2 삭제시 연관된 club들도 삭제되어야 한다. 이때 people3에도 같은 club 관계되어 있다면 해당 club 삭제할까? 삭제하지 않을까?
결론적으로는 삭제된다.

따라서 people3 club 갯수가 2 였지만 people2 삭제하면서 people3 club 갯수가 1개로 변했다. people2 삭제시 관계된 club 그냥 삭제된다.

주의 :  CascadeType.ALL (CascadeType.REMOVE) 원하는 로직이 무언인지 판단하고 사용해야한다. 글쓴이는 관계가 완전히 종속적인 관계가 아니라면 쓰지않는다.

 

 

 

 

 

 

 

ManyToMany(Unidirectional(단방향))

 

위의 양방향 예제에서 people에서 club으로의 관계만 없이 club에서 people로의 관계만 있는 형태이다.

행동은 단방향 ManyToOne 동일하다.

 

따라서 예제는 작성하지 않는다.( 귀찮다 ㅜㅜ)

 


반응형