我想通過一個可能無意義的問題得到一些建議,或者可能會這樣做。讓我們有一組利益,像這樣一個Many2Many關係的配置文件對象:JPA/Hibernate中的多對多關係Eager
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name="profile_interests",
joinColumns={ @JoinColumn(name="profile_id") },
inverseJoinColumns = { @JoinColumn(name="interest_id") })
@OrderColumn(name="display_order")
private Set<Interest> interests;
//GETTER AND SETTERS
public Set<Interest> getInterests() {
return interests;
}
public void setInterests(Set<Interest> interests) {
this.interests = interests;
}
public void addInterest(Interest interest) {
interests.add(interest);
}
public void removeInterest(String interestName) {
interests.remove(new Interest(interestName));
}
在我的應用程序控制器我可以通過這種方式添加和刪除的利益。
@RequestMapping(value="/save-interest", method=RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> saveInterest(@RequestParam("name") String interestName) {
SiteUser user = getUser();
Profile profile = profileService.getUserProfile(user);
String cleanedInterestName = htmlPolicy.sanitize(interestName);
Interest interest = interestService.createIfNotExists(cleanedInterestName);
profile.addInterest(interest);
profileService.save(profile);
return new ResponseEntity<>(null, HttpStatus.OK);
}
@RequestMapping(value="/delete-interest", method=RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> deleteInterest(@RequestParam("name") String interestName) {
SiteUser user = getUser();
Profile profile = profileService.getUserProfile(user);
profile.removeInterest(interestName);
profileService.save(profile);
return new ResponseEntity<>(null, HttpStatus.OK);
}
最終,將創建一個配置文件,一個profile_interests和一個興趣表。 profile_interest表將有一個profile_id和一個interest_id,對吧?
現在想象一下,我還想讓其他套裝讓我們說:活動,激情或討厭,厭惡,任務,職業。我可以一次又一次地重複這些相同的過程,以涵蓋6個新的(活動,激情,仇恨,不喜歡,任務,職業)。
在某些時候,一個人可能對汽車有興趣,其他人對汽車有興趣,第三個人討厭汽車,第四個人說汽車是他的職業。
如果我創建了7個不同的對象集(興趣,活動,激情,討厭,不喜歡,任務,職業),我會在所有表中重複其中的很多。
- 有沒有辦法讓7組對象具有共同的(興趣,活動,激情,討厭,不喜歡,任務,職業)表,但7個不同的中間表(profile_interests,profile_activities,profile_passions,profile_hates ,profile_dislikes,profile_task,profile_vocation)使用公共表?
謝謝。非常感謝您與非程序員的幫助。可能這是一個有據可查的問題,我已經解決了,我不知道。
PD:該利益實體是在這裏:
@Entity
@Table(name = "interests")
public class Interest implements Comparable<Interest> {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "interest_name", unique = true, length = 25)
private String name;
public Interest() {
}
將'fetchType'設置爲'EAGER'對'Many2Many'關係不好,特別是你有多個。 –
感謝哈迪,如果我多次使用它,我會重新提出你的建議,但這正是我試圖避免的(多次使用它)。有關如何做的建議? – Mike
這是可能的,但並不像您想要的那樣直截了當:您需要映射7個對象,每個對象一個:profile_interests,profile_activities,profile_passions,profile_hates,profile_dislikes,profile_task,profile_vocation – Boschi