단방향 및 양방향 JPA와 최대 절전 모드 연결의 차이점은 무엇입니까?
단방향 및 양방향 연관의 차이점은 무엇입니까?
db에서 생성 된 테이블이 모두 같기 때문에 내가 찾은 유일한 차이점은 입찰 관계의 각면이 다른 쪽을 참조하고 단방향은 참조하지 않는다는 것입니다.
이것은 단방향 연결입니다
public class User {
private int id;
private String name;
@ManyToOne
@JoinColumn(
name = "groupId")
private Group group;
}
public class Group {
private int id;
private String name;
}
양방향 연관
public class User {
private int id;
private String name;
@ManyToOne
@JoinColumn(
name = "groupId")
private Group group;
}
public class Group {
private int id;
private String name;
@OneToMany(mappedBy="group")
private List<User> users;
}
차이점은 그룹이 사용자에 대한 참조를 보유하는지 여부입니다.
이것이 유일한 차이점인지 궁금합니다. 어느 것이 권장됩니까?
주된 차이점은 양방향 관계가 양방향으로 탐색 액세스를 제공하므로 명시적인 쿼리없이 다른쪽에 액세스 할 수 있다는 것입니다. 또한 계단식 옵션을 양방향에 적용 할 수 있습니다.
특히 "일대 다"및 "다 대다"관계의 경우 탐색 액세스가 항상 좋은 것은 아닙니다. Group
수천 개의을 포함 하는 a 를 상상해보십시오 User
.
그들에게 어떻게 접근하겠습니까? 너무 많은
User
s를 사용하면 일반적으로 필터링 및 페이지 매김을 적용해야하므로 쿼리를 실행해야합니다 ( 컬렉션 필터링 을 사용하지 않는 한 나에게 해킹처럼 보입니다). 이러한 경우 일부 개발자는 메모리에 필터링을 적용하는 경향이 있으며 이는 성능에 좋지 않습니다. 이러한 관계가 있으면 이러한 종류의 개발자가 성능에 영향을주지 않고 관계를 사용할 수 있습니다.How would you add new
User
s to theGroup
? Fortunately, Hibernate looks at the owning side of relationship when persisting it, so you can only setUser.group
. However, if you want to keep objects in memory consistent, you also need to addUser
toGroup.users
. But it would make Hibernate to fetch all elements ofGroup.users
from the database!
So, I can't agree with the recommendation from the Best Practices. You need to design bidirectional relationships carefully, considering use cases (do you need navigational access in both directions?) and possible performance implications.
See also:
There are two main differences.
Accessing the association sides
The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.
So, for a unidirectional @ManyToOne
association, it means you can only access the relationship from the child side where the foreign key resides.
If you have a unidirectional @OneToMany
association, it means you can only access the relationship from the parent side where the foreign key resides.
For the bidirectional @OneToMany
association, you can navigate the association in both ways, either from the parent or from the child side.
You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.
Performance
The second aspect is related to performance.
- For
@OneToMany
, unidirectional associations don't perform as well as bidirectional ones. - For
@OneToOne
, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value. - For
@ManyToMany
, the collection type makes quite a difference asSets
perform better thanLists
.
In terms of coding, a bidirectional relationship is more complex to implement because the application is responsible for keeping both sides in synch according to JPA specification 5 (on page 42). Unfortunately the example given in the specification does not give more details, so it does not give an idea of the level of complexity.
When not using a second level cache it is usually not a problem to do not have the relationship methods correctly implemented because the instances get discarded at the end of the transaction.
When using second level cache, if anything gets corrupted because of wrongly implemented relationship handling methods, this means that other transactions will also see the corrupted elements (the second level cache is global).
A correctly implemented bi-directional relationship can make queries and the code simpler, but should not be used if it does not really make sense in terms of business logic.
I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html
Specifically:
Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.
I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.
'Programing' 카테고리의 다른 글
Apache Thrift, Google Protocol Buffers, MessagePack, ASN.1 및 Apache Avro의 주요 차이점은 무엇입니까? (0) | 2020.07.13 |
---|---|
canvas.toDataURL ()을 사용하여 캔버스를 이미지로 저장하는 방법? (0) | 2020.07.13 |
Android 기기에 신뢰할 수있는 CA 인증서를 설치하는 방법은 무엇입니까? (0) | 2020.07.13 |
구체적인 URL을 제외 할 수 있습니까? (0) | 2020.07.13 |
위도와 경도에 대한 데이터 유형은 무엇입니까? (0) | 2020.07.13 |