programing

1 대 다, 다 대 1 및 다 대 다의 차이점

prostudy 2022. 6. 19. 18:06
반응형

1 대 다, 다 대 1 및 다 대 다의 차이점

네, 이것은 아마 사소한 질문일 것입니다만, 그 차이와 각각의 사용 타이밍을 시각화하고 이해하는 데 어려움을 겪고 있습니다.단방향 및 양방향 매핑과 같은 개념이 일대다/다대다 관계에 어떤 영향을 미치는지도 잘 모르겠습니다.저는 지금 휴지기를 사용하고 있기 때문에 ORM과 관련된 설명이 있으면 도움이 됩니다.

예를 들어 다음과 같은 설정이 있다고 가정합니다.

public class Person{
    private Long personId;
    private Set<Skill> skills;
    //Getters and setters
}

public class Skill{
    private Long skillId;
    private String skillName;
    //Getters and setters
}

이 경우 어떤 종류의 매핑이 필요합니까?이 구체적인 예에 대한 답변은 물론 감사하지만, 1 대 다와 다 대 다 중 하나를 사용해야 하는 시기와 조인 테이블 대 조인 열 및 단방향 대 쌍방향 중 하나를 사용해야 하는 시점의 개요를 알고 싶습니다.

것 같다One-to-many ★★Many-to-many:

「 」의 One-to-many,Many-to-one ★★★★★★★★★★★★★★★★★」Many-to-Many 말합니다

One-to-many vs는 관점의 문제입니다. Unidirectional »Bidirectional는 매핑에 영향을 주지 않지만 데이터에 액세스하는 방법에 영향을 미칩니다.

  • »Many-to-onemany에서는, 을 참조합니다.one'도시가 있다 경우, 「 」State과 '단측'입니다.City하다, , 하다, 하다, 칸이 나옵니다.state_idcities.

단방향으로,Person에는 「」가 있습니다.List<Skill> skillsSkill 갖지 않다Person person양방향에서는 두 속성이 모두 추가되며 이 속성을 통해Person기술이 주어지다(예: skill.person를 참조해 주세요.

  • »One-to-Many한쪽이 우리의 기준점이 될 것입니다.주소는 사용자에게 있습니다.에는 세 수 있습니다.address_1_id,address_2_id ★★★★★★★★★★★★★★★★★」address_3_id또는 다중 열 고유 제약 조건이 있는 룩업 테이블user_idaddress_id.

단방향에서는User 가지다Address address. 양방향에는 추가 정보가 있습니다.List<User> users Address를 누릅니다

  • »Many-to-Many각 당사자의 구성원은 상대방의 임의의 수의 구성원을 참조할 수 있습니다.를 위해 룩업 테이블을 사용합니다.이에 대한 예로는 의사와 환자의 관계가 있다.의사는 많은 환자를 가질 수 있고 그 반대의 경우도 있다.

일대다: 1명이 여러 스킬을 가지고 있어 스킬은 개인간에 재사용되지 않는다.

  • 단방향성: 스킬 세트를 통해 스킬을 직접 참조할 수 있습니다.
  • 양방향:각 "자녀" 스킬에는 개인에 대한 포인터가 1개씩 있습니다(코드에 표시되지 않음).

Multi-to-Mody: 한 사람이 여러 스킬을 가지고 있으며, 한 스킬은 다른 사람 간에 재사용됩니다.

  • 단방향성: 스킬 세트를 통해 스킬을 직접 참조할 수 있습니다.
  • 양방향:스킬에는 스킬과 관련된 일련의 사용자가 있습니다.

일대다 관계에서 한 개체는 "부모"이고 다른 개체는 "자녀"입니다.부모가 자녀의 존재를 통제한다.Multi-to-Many에서 두 유형의 존재는 두 유형의 외부(대규모 애플리케이션 컨텍스트)에 의존합니다.

대상(도메인)은 관계가 1대 다인지 다대 다인지를 지시해야 합니다.다만, 단방향인지 쌍방향인지를 결정하는 것은 메모리, 처리, 퍼포먼스 등을 교환하는 엔지니어링상의 결정이라고 생각합니다.

혼란스러울 수 있는 것은 다대다 쌍방향 관계가 대칭일 필요는 없다는 것입니다.즉, 많은 사람들이 기술을 가리킬 수 있지만, 그 기술이 그 사람들만 관련지어질 필요는 없습니다.보통 그렇겠지만, 그런 대칭성은 필수가 아닙니다.예를 들어, 사랑은 쌍방향이지만 종종 비대칭적인('사랑하지만 그녀는 나를 사랑하지만 그녀는 나를 사랑하지 않는다.

이 모든 것은, 휴지 상태 및 JPA 로 충분히 서포트되고 있습니다.Hibernate나 다른 ORM은 쌍방향 다대다 관계를 관리할 때 대칭성을 유지하는 데 전혀 관심이 없다는 것을 기억하십시오.모든 것은 어플리케이션에 달려 있습니다.

1) 원은 엔티티/POJO/빈입니다.

2) deg는 그래프와 같이 도(엣지 수)의 약어입니다.

PK=기본 키, FK=외부 키

정도와 변의 이름 사이의 모순에 주목하십시오.대부분은 도=1에 해당하는 반면, 1은 도 >1에 해당합니다.

1 대 다 다 대 1대 다의 그림

일대다

1 대 다의 테이블 관계는 다음과 같습니다.

일대다

는 2개의 을 1개의 .Foreign Key에서 " "를 합니다.Primary Key1번으로 하다

표 에서 " "는post_idpost_comment에는 table table table table table a a a a a a a가 있다.Foreign Key와의 post ID '' 아이디Primary Key§:

    ALTER TABLE
        post_comment
    ADD CONSTRAINT
        fk_post_comment_post_id
    FOREIGN KEY (post_id) REFERENCES post

@ManyToOne 주석

다 를 매핑하는 은 JPA를 하는 입니다.@ManyToOne석입니니다다

경우, 「」는PostComment는 " "를 .post_id[ Foreign Key ]를 하는 [@ManyToOne★★★★

    @Entity(name = "PostComment")
    @Table(name = "post_comment")
    public class PostComment {
    
        @Id
        @GeneratedValue
        private Long id;
    
        private String review;
    
        @ManyToOne(fetch = FetchType.LAZY)
        private Post post;
        
    }

JPA @OneToMany

「 」를 할 수 있는 만으로,@OneToMany주석은 모든 1대 다 데이터베이스 관계에 대해 기본 옵션이 되어야 한다는 의미는 아닙니다.

JPA 수집의 문제는 요소 수가 다소 적을 때만 사용할 수 있다는 것입니다.

@OneToMany입니다.@ManyToOne" " " " " " " " 측:

    @Entity(name = "Post")
    @Table(name = "post")
    public class Post {
    
        @Id
        @GeneratedValue
        private Long id;
    
        private String title;
    
        @OneToMany(
            mappedBy = "post", 
            cascade = CascadeType.ALL, 
            orphanRemoval = true
        )
        private List<PostComment> comments = new ArrayList<>();
    
        //Constructors, getters and setters removed for brevity
    
        public void addComment(PostComment comment) {
            comments.add(comment);
            comment.setPost(this);
        }
    
        public void removeComment(PostComment comment) {
            comments.remove(comment);
            comment.setPost(null);
        }
    }

Post '유틸리티')를 갖추고 있습니다.addComment ★★★★★★★★★★★★★★★★★」removeComment쌍방향 어소시에이션의 양쪽을 동기화하기 위해서 사용됩니다.

쌍방향 어소시에이션을 취급할 때는 항상 이러한 방법을 지정해야 합니다.그렇지 않으면 매우 미묘한 상태의 전파 문제가 발생할 위험이 있습니다.

" " "@OneToMany사용법이 덜이기 때문에 .@ManyToOne 쌍방향의 「」를 참조해 주세요.@OneToMany★★★★★★ 。

일대일

1 대 1 테이블 관계는 다음과 같습니다.

일대일

1 테이블 는 2개의 을 1:1로 합니다.Primary Key은 ''이기도 .Foreign KeyPrimary Key★★★★★★★★★★★★★★★★★★★★★★★★★★★

때문에은 '', '', ' 밥상', '아기 밥상'이라고 할 수 .Primary Key부모 테이블과 함께 사용합니다.

표 에서 " "는idpost_details에는 「」도 .Foreign Key와의 post '''id Primary Key§:

    ALTER TABLE
        post_details
    ADD CONSTRAINT
        fk_post_details_id
    FOREIGN KEY (id) REFERENCES post

JPA @OneToOne@MapsId의 표시)

@OneToOne관계는 사용하는 것입니다.@MapsId에 쌍방향 이것은, 항상, 이 어소시에이션을 취득할 수 있기 때문입니다.PostDetails: " " 를 하여 엔티티로 사용합니다.Post엔티티 아이디

매핑은 다음과 같습니다.

@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails {

    @Id
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "id")
    private Post post;

    public PostDetails() {}

    public PostDetails(String createdBy) {
        createdOn = new Date();
        this.createdBy = createdBy;
    }

    //Getters and setters omitted for brevity
}

하면, 「 」는id속성은 기본 키와 외부 키 역할을 모두 수행합니다.@Id에 더 "A"를 .@GeneratedValue에는 '아노메이션'의 식별자가 되어 있기 을 붙입니다.post★★★★★★ 。

다대다

다대다 테이블 관계는 다음과 같습니다.

다대다

테이블 는 2개의 부모 하는 자녀 을 통해 합니다.자에는 2개의 부모 테이블이 포함되어 있습니다.Foreign KeyPrimary Key2개입니다.

표 에서 " "는post_idpost_tag에는 「」도 .Foreign Key와의 post ID '' 아이디Primary Key§:

    ALTER TABLE
        post_tag
    ADD CONSTRAINT
        fk_post_tag_post_id
    FOREIGN KEY (post_id) REFERENCES post

tag_idpost_tag에는 table table table table table a a a a a a a가 있다.Foreign Key와의 tag ID '' 아이디Primary Key§:

    ALTER TABLE
        post_tag
    ADD CONSTRAINT
        fk_post_tag_tag_id
    FOREIGN KEY (tag_id) REFERENCES tag

JPA @ManyToMany

맵을 수 .many-to-manyJPA:

    @Entity(name = "Post")
    @Table(name = "post")
    public class Post {

        @Id
        @GeneratedValue
        private Long id;

        private String title;

        @ManyToMany(cascade = { 
            CascadeType.PERSIST, 
            CascadeType.MERGE
        })
        @JoinTable(name = "post_tag",
            joinColumns = @JoinColumn(name = "post_id"),
            inverseJoinColumns = @JoinColumn(name = "tag_id")
        )
        private Set<Tag> tags = new HashSet<>();

        //Getters and setters ommitted for brevity

        public void addTag(Tag tag) {
            tags.add(tag);
            tag.getPosts().add(this);
        }

        public void removeTag(Tag tag) {
            tags.remove(tag);
            tag.getPosts().remove(this);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Post)) return false;
            return id != null && id.equals(((Post) o).getId());
        }

        @Override
        public int hashCode() {
            return getClass().hashCode();
        }
    }

    @Entity(name = "Tag")
    @Table(name = "tag")
    public class Tag {

        @Id
        @GeneratedValue
        private Long id;

        @NaturalId
        private String name;

        @ManyToMany(mappedBy = "tags")
        private Set<Post> posts = new HashSet<>();

        //Getters and setters ommitted for brevity

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Tag tag = (Tag) o;
            return Objects.equals(name, tag.name);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name);
        }
    }
  1. tagsPost에서는 '만'을 정의합니다.PERSIST ★★★★★★★★★★★★★★★★★」MERGE ★★★★★REMOVE 상태의 「이행」이나 「이행」에 .@ManyToManyJPA 어소시에이션은 체인 삭제를 트리거하여 최종적으로 어소시에이션의 양쪽을 소거할 가능성이 있기 때문입니다.
  2. add/remove 유틸리티 메서드는 어소시에이션의 양쪽이 동기화되도록 하기 위해 쌍방향 어소시에이션을 사용하는 경우 필수입니다.
  3. Post엔티티에는 고유한 비즈니스 키가 없기 때문에 엔티티 식별자를 동등하게 사용합니다.엔티티 ID는 모든 엔티티 상태 전환 간에 일관성을 유지하는 한 동일한 엔티티 ID를 사용할 수 있습니다.
  4. Tag에는 Hibernate 이는 Hibernate 고유의 것으로 마크되어 .@NaturalId주석입니다.그럴 때는 독특한 비즈니스 키가 평등 점검에 가장 적합한 후보입니다.
  5. mappedBy「」의 postsTag 쌍방향에서 엔티티는 " "를.Post이치노이것은 한쪽만 관계를 소유할 수 있고 변경은 이 특정 쪽에서 데이터베이스에만 전파되기 때문에 필요합니다.
  6. Set를 사용하는 것이 바람직하다.List@ManyToMany효율이 떨어집니다.

기사 "Mapping Object Relations"를 참조하십시오.

매핑할 때 고려해야 할 객체 관계에는 두 가지 범주가 있습니다.첫 번째 범주는 다중성에 기반하며 다음 세 가지 유형을 포함합니다.

*One-to-one relationships.  This is a relationship where the maximums of each of its multiplicities is one, an example of which is holds relationship between Employee and Position in Figure 11.  An employee holds one and only one position and a position may be held by one employee (some positions go unfilled).
*One-to-many relationships. Also known as a many-to-one relationship, this occurs when the maximum of one multiplicity is one and the other is greater than one.  An example is the works in relationship between Employee and Division.  An employee works in one division and any given division has one or more employees working in it.
*Many-to-many relationships. This is a relationship where the maximum of both multiplicities is greater than one, an example of which is the assigned relationship between Employee and Task.  An employee is assigned one or more tasks and each task is assigned to zero or more employees. 

두 번째 범주는 방향성에 기초하고 단방향 관계와 양방향 관계 두 가지 유형을 포함합니다.

*Uni-directional relationships.  A uni-directional relationship when an object knows about the object(s) it is related to but the other object(s) do not know of the original object.  An example of which is the holds relationship between Employee and Position in Figure 11, indicated by the line with an open arrowhead on it.  Employee objects know about the position that they hold, but Position objects do not know which employee holds it (there was no requirement to do so).  As you will soon see, uni-directional relationships are easier to implement than bi-directional relationships.
*Bi-directional relationships.  A bi-directional relationship exists when the objects on both end of the relationship know of each other, an example of which is the works in relationship between Employee and Division.  Employee objects know what division they work in and Division objects know what employees work in them. 

그런 식으로 설명하겠습니다.

일대일 - 일대일 관계

@OneToOne
Person person;

@OneToOne
Nose nose;

일대다 - 다대일 관계

@OneToMany
Shepherd> shepherd;

@ManyToOne
List<Sheep> sheeps;

Many To Many - Many To Many 관계

@ManyToMany
List<Traveler> travelers;

@ManyToMany
List<Destination> destinations;

이것은 아마도 다음과 같은 다대다 관계 선박을 필요로 할 것이다.



public class Person{

    private Long personId;
    @manytomany

    private Set skills;
    //Getters and setters
}

public class Skill{
    private Long skillId;
    private String skillName;
    @manyToMany(MappedBy="skills,targetClass="Person")
    private Set persons; // (people would not be a good convenion)
    //Getters and setters
}

joinTable + JoinColumn을 정의해야 할 수도 있지만, 다음과 같은 작업이 필요하지 않습니다.

우선, 모든 세부 사항을 읽어보세요.NHibernate(따라서 Hibernate도 마찬가지라고 생각됩니다) 관계 매핑은 DB 및 객체 그래프 매핑과 재미있는 대응 관계가 있습니다.예를 들어, 일대일 관계는 종종 다대일 관계로 구현됩니다.

둘째, O/R 맵 작성 방법을 설명하기 전에 DB도 확인해야 합니다.특히 하나의 스킬을 여러 사람이 소유할 수 있습니까?그렇다면 다대다로, 그렇지 않으면 다대1로 관계를 맺을 수 있습니다.

셋째, 다대다 관계를 직접 구현하는 것이 아니라 도메인 모델에서 "join table"을 모델링하는 것을 선호합니다. 즉, 다음과 같이 엔티티로 취급합니다.

class PersonSkill 
{
    Person person;
    Skill skill;    
}

그럼 네가 가진 게 보이니?2개의 1대 다 관계가 있습니다.(이 경우 개인은 개인 스킬 컬렉션을 가질 수 있지만 스킬 컬렉션은 가질 수 없습니다.)그러나 일부에서는 (사람과 스킬 사이에) 다대다 관계를 사용하는 것을 선호합니다.이것은 논란의 여지가 있습니다.

넷째, 쌍방향 관계(예를 들어, 개인은 스킬의 컬렉션뿐만 아니라 스킬은 사람의 컬렉션도 가지고 있다)가 있는 경우, NHibernate는 BL에 쌍방향성을 강제하지 않고, 지속성을 목적으로 하는 관계의 쌍방향성만을 파악합니다.

다섯째, 다대다(컬렉션 맵핑)보다 NHibernate(및 휴지 상태)에서 올바르게 사용하는 것이 훨씬 쉽습니다.

행운을 빕니다.

언급URL : https://stackoverflow.com/questions/3113885/difference-between-one-to-many-many-to-one-and-many-to-many

반응형