Java Persistence/ManyToOne

From Wikibooks, open books for an open world
Jump to: navigation, search

 

 

ManyToOne[edit]

ObjectRelational-ManyToOne2.jpg

A ManyToOne relationship in Java is where the source object has an attribute that references another object, the target object. I.e. the rather typical Java case that one object holds a reference to another object. A ManyToOne relationship can be specified unidirectional. However, it is typical that the target object has the inverse relationship specified back to the source object. This would be a OneToMany relationship specification in the target object. All relationships in Java and JPA are unidirectional, in that if a source object references a target object there is no guarantee that the target object also has a relationship to the source object. This is different than a relational database, in which relationships are defined through foreign keys and querying such that the inverse query always exists.

In JPA a ManyToOne relationship is specified through the @ManyToOne annotation or the <many-to-one> element. A @ManyToOne annotation is typically accompanied by a @JoinColumn annotation. The @JoinColumn annotation specifies how the relationship should be mapped to (expressed in) the database. The @JoinColumn defines the name of the foreign key column (@JoinColumn(name = "...")) in the source object that should be used to find (join) the target object.

If the reverse OneToMany relationship is specified in the target object, then the @OneToMany annotation in the target object must contain a mappedBy attribute to define this inverse relation.

JPA also defines a OneToOne relationship, which is similar to a ManyToOne relationship, except that the inverse relationship (if it were defined) is a OneToOne relationship. The main difference between a OneToOne and a ManyToOne relationship in JPA is that a ManyToOne always contains a foreign key from the source object's table to the target object's table, whereas a OneToOne relationship the foreign key may either be in the source object's table or the target object's table.

Example of a ManyToOne relationship database[edit]

EMPLOYEE (table)

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

EMP_ID FIRSTNAME LASTNAME SALARY MANAGER_ID
1 Bob Way 50000 2
2 Sarah Smith 75000 null

PHONE (table)

ID TYPE AREA_CODE P_NUMBER OWNER_ID
1 home 613 792-0000 1
2 work 613 896-1234 1
3 work 416 123-4444 2

Example of a ManyToOne relationship annotations[edit]

@Entity
public class Phone {
  @Id
  private long id;
  ...
  // Specifies the PHONE table does not contain an owner column, but 
  // an OWNER_ID column with a foreign key. And creates a join to
  // lazily fetch the owner
  @ManyToOne(fetch=FetchType.LAZY)
  @JoinColumn(name="OWNER_ID")
  private Employee owner;
  ...
}

// Specification of the reverse OneToMany relationship in Employee
@Entity
public class Employee {
  @Id
  private long emp_id;
  ...
  // The 'mappedBy = "owner"' attribute specifies that
  // the 'private Employee owner;' field in Phone owns the
  // relationship (i.e. contains the foreign key for the query to
  // find all phones for an employee.)
  @OneToMany(mappedBy = "owner")
  private List<Phone> phones;
  ...

Example of a ManyToOne relationship XML[edit]

<entity name="Phone" class="org.acme.Phone" access="FIELD">
    <attributes>
        <id name="id"/>
        <many-to-one name="owner" fetch="LAZY">
            <join-column name="OWNER_ID"/>
        </many-to-one>
    </attributes>
</entity>

See Also[edit]

Common Problems[edit]

Foreign key is also part of the primary key.[edit]
See Primary Keys through OneToOne Relationships.
Foreign key is also mapped as a basic.[edit]
If you use the same field in two different mappings, you typically require to make one of them read-only using insertable, updateable = false.
See Target Foreign Keys, Primary Key Join Columns, Cascade Primary Keys.
Constraint error on insert.[edit]
This typically occurs because you have incorrectly mapped the foreign key in a OneToOne relationship.
See Target Foreign Keys, Primary Key Join Columns, Cascade Primary Keys.
It can also occur if your JPA provider does not support referential integrity, or does not resolve bi-directional constraints. In this case you may either need to remove the constraint, or use EntityManager flush() to ensure the order your objects are written in.
Foreign key value is null[edit]
Ensure you set the value of the object's OneToOne, if the OneToOne is part of a bi-directional OneToMany relationship, ensure you set the object's OneToOne when adding an object to the OneToMany, JPA does not maintain bi-directional relationships for you.
Also check that you defined the JoinColumn correctly, ensure you did not set insertable, updateable = false or use a PrimaryKeyJoinColumn.

Advanced[edit]

Target Foreign Keys, Primary Key Join Columns, Cascade Primary Keys[edit]

In complex data models it may be required to use a target foreign key, or read-only JoinColumn in mapping a ManyToOne if the foreign key/JoinColumn is shared with other ManyToOne or Basic mappings.

See, Target Foreign Keys, Primary Key Join Columns, Cascade Primary Keys

 

[출처] https://en.wikibooks.org/wiki/Java_Persistence/ManyToOne

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
35 [EMF] EMF Tutorial EMF 튜터리얼 file 졸리운_곰 2023.08.23 298
34 Eclipse RAP Tutorial for Beginners - Workbench Application (OLD) file 졸리운_곰 2021.01.30 334
33 Learn Eclipse GMF in 15 minutes file 졸리운_곰 2019.11.27 254
32 [Eclipse] GEF entry series (10, an implementation of the form) file 졸리운_곰 2019.11.25 217
31 GEF Programmer Guide 번역 졸리운_곰 2019.11.25 230
30 Learn Eclipse GMF in 15 minutes file 졸리운_곰 2019.11.20 233
29 RCP 에디터 정리 졸리운_곰 2019.11.20 338
28 다른 그림과 관련하여 GEF 편집기 레이아웃에서 그림의 위치 제한 조건을 동적으로 계산 Dynamically calculating the position constraints for a figure in a GEF editor layout in relation to another figure file 졸리운_곰 2019.11.20 285
27 RCP 등에서 .mf 파일로 다른 프로젝트 익스포트 포함시 라이브러리(메소드)를 찾지 못할 때, Eclipse RCP - cant resolve importing libraries in final build file 졸리운_곰 2019.10.15 419
26 ESE2006-EclipseModelingSymposium15_GMF.pdf file 졸리운_곰 2019.09.21 307
25 GMF_Creation_Review.pdf file 졸리운_곰 2019.09.21 380
24 Eclipse EMF and GMF Tutorial file 졸리운_곰 2019.09.21 225
23 GMF Tutorial/ko file 졸리운_곰 2019.09.20 363
22 Model Driven Architecture approach to domain of graphical editors file 졸리운_곰 2019.09.20 273
21 Single_Sourcing_RAP_RCP_en.pdf file 졸리운_곰 2019.05.15 313
20 Rich client platform 설명 및 배우기 참고 졸리운_곰 2019.05.15 319
19 Rich Ajax Platform, Part 1: 소개 file 졸리운_곰 2019.05.15 333
18 또 하나의 크로스 플랫폼: Eclipse RAP file 졸리운_곰 2019.05.15 328
17 Eclipse 4 RCP 튜토리얼(완료) file 졸리운_곰 2019.05.14 997
16 Updating UI in Eclipse RCP 졸리운_곰 2015.11.07 425
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED