Spring Data JPA Many To Many 양방향관계예제 오라클자바커뮤니티 (ojc.asia, ojcedu.com)
엔티티매핑 (Entity Mapping) M : N 연관관계 사원 (Sawon), 취미 (Hobby) 는다 : 다관계이다. 사원은여러취미를가질수있고, 하나의취미역시여러사원에할당될수있기때문이다. 보통관계형 DB 에서는다 : 다관계는 1 : 다, 다 : 1 로나누어서풀게된다. 그러나객체에서는 2 개의객체로다 : 다관계를만드는데, 사원에서취미를컬렉션에넣어접근가능하고, 반대로취미에서도사원들을컬렉션에넣어접근하면양쪽에서접근이가능하다. 다 : 다매핑을위해 @ManyToMany 어노테이션을사용한다. SAWO N # id name # id name HOBB Y # sawon_id # hobby_id SAWON_HOBBY 2
엔티티매핑 (Entity Mapping) M : N 양방향연관관계 @ManyToMany 어노테이션에 mapsby 속성을사용하여연관관계의주인을지정한다. (mappedby 가없는곳이 Owner 이다 ) SAWO N # id name # id name HOBB Y # sawon_id # hobby_id SAWON_HOBBY Sawon Id : Long name : String hobbies : Hobby +sawons +hobbies * * Hobby id : Long name : String sawons : Sawon 3
엔티티매핑 (Entity Mapping) M : N, 양방향예제 (1) src/main/resources/application.properties STS -> Spring Stater Project name : manytomany Data : JPA DataBase : MySQL spring.datasource.platform=mysql spring.datasource.url=jdbc:mysql://localhost/manyto many?createdatabaseifnotexist=true spring.datasource.username=root spring.datasource.password=1111 spring.datasource.driver-classname=com.mysql.jdbc.driver spring.datasource.sql-script-encoding=utf-8 spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true 4
엔티티매핑 (Entity Mapping) M : N, 양방향예제 (2) demo.model.sawon.java @Entity public class Sawon { private Long id; private String name; private Set<Hobby> hobbies; public Sawon(String name, Set<Hobby> hobbies) { this.name = name; this.hobbies = hobbies; public Sawon(Long id, String name, Set<Hobby> hobbies) { super(); this.id = id; this.name = name; this.hobbies = hobbies; public Sawon() { @Id @GeneratedValue public Long getid() { return id; public void setid(long id) { this.id = id; public String getname() { return name; public void setname(string name) { this.name = name; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "sawon_hobby", joincolumns = @JoinColumn(name = "sawon_id", referencedcolumnname = "id"), inversejoincolumns = @JoinColumn(name = "hobby_id", referencedcolumnname = "id") ) public Set<Hobby> gethobbies() { return hobbies; public void sethobbies(set<hobby> hobbies) { this.hobbies = hobbies; public String tostring() { String result = String.format("Sawon [id=%d, name='%s']%n", id, name); if (hobbies!= null) { for (Hobby hobby : hobbies) { result += String.format("Hobby[id=%d, name='%s']%n", hobby.getid(), hobby.getname()); return result; 5
엔티티매핑 (Entity Mapping) M : N, 양방향예제 (3) demo.model.hobby.java @Entity public class Hobby { private Long id; private String name; private Set<Sawon> sawons; public Hobby() { public Hobby(String name) { this.name = name; public Hobby(Long id, String name) { this.id = id; this.name = name; public Hobby(Long id, String name, Set<Sawon> sawons) { this.id = id; this.name = name; this.sawons = sawons; @Id @GeneratedValue public Long getid() { return id; public void setid(long id) { this.id = id; public String getname() { return name; public void setname(string name) { this.name = name; @ManyToMany(mappedBy = "hobbies") public Set<Sawon> getsawons() { return sawons; public void setsawons(set<sawon> sawons) { this.sawons = sawons; demo.repository.sawonrepository.ja va package demo.repository; import org.springframework.data.jpa.repository.jpa Repository; import demo.model.sawon; public interface SawonRepository extends JpaRepository<Sawon, Long>{ 6
엔티티매핑 (Entity Mapping) M : N, 양방향예제 (4) demo.manytomanyapplication.java @SpringBootApplication public class ManytomanyApplication implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(ManytomanyApplica tion.class); public static void main(string[] args) { SpringApplication.run(ManytomanyApplicatio n.class, args); @Autowired SawonRepository sawonrepository; sawonrepository.save(new HashSet<Sawon>() { { add(new Sawon("1 길동 ", new HashSet<Hobby>() { { add(h1); add(h2); )); add(new Sawon("2 길동 ", new HashSet<Hobby>() { { add(h2); add(h3); )); add(new Sawon("3 길동 ", new HashSet<Hobby>() { { add(h1); add(h3); )); ); @Transactional public void run(string...args) { Hobby h1 = new Hobby(" 등산 "); Hobby h2 = new Hobby(" 골프 "); Hobby h3 = new Hobby(" 여행 "); for(sawon s : sawonrepository.findall()) { logger.info(s.tostring()); 7
엔티티매핑 (Entity Mapping) M : N, 양방향예제 (5) 데이터확인하기 [ 테이블셍성스크립트 ] Hibernate: create table hobby (id bigint not null auto_increment, name varchar(255), primary key (id)) Hibernate: create table sawon (id bigint not null auto_increment, name varchar(255), primary key (id)) Hibernate: create table sawon_hobby (sawon_id bigint not null, hobby_id bigint not null, primary key (sawon_id, hobby_id)) Hibernate: alter table sawon_hobby add constraint FK_p9uwrr1nddt9pgue7xqmey4cr foreign key (hobby_id) references hobby (id) Hibernate: alter table sawon_hobby add constraint FK_qqk3c8ippcim47nrhxyislbtl foreign key (sawon_id) references sawon (id) 8