1
Same question here, but it didn't help meJPA ManyToMany在用戶和組的情況下?
我有三個表和多對多的連接。在我的JSF應用程序中,我試圖添加用戶。在我的組表中有三個不同的組:管理員,客戶和用戶。
我做了什麼:
- 插入數據JSF型用戶點擊後保存。
- ManagedBean調用usersController從groupsController獲取組(customer-group)
- usersController ManagedBean創建新用戶並將其保存到mySQL-db。
- 問題是groups_has_user-表是空的
和代碼
用戶:
public class Users implements Serializable {
@ManyToMany(mappedBy = "usersCollection")
private Collection<Groups> groupsCollection;
羣組:
public class Groups implements Serializable {
@JoinTable(name = "groups_has_user", joinColumns = {
@JoinColumn(name = "groups_group_id", referencedColumnName = "group_id", nullable = false)}, inverseJoinColumns = {
@JoinColumn(name = "user_username", referencedColumnName = "username", nullable = false)})
@ManyToMany
private Collection<Users> usersCollection;
UsersController-managedBean
// current is type Users
current.setIsCustomer(Boolean.TRUE);
//BalusC!! Why this is not working but the one below is?
//FacesContext facesContext = FacesContext.getCurrentInstance();
//HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
//GroupsController groupsC = (GroupsController)session.getAttribute("groupsController");
FacesContext context = FacesContext.getCurrentInstance();
GroupsController groupsC = (GroupsController) context.getApplication().evaluateExpressionGet(context, "#{groupsController}", GroupsController.class);
// Fetching group number 2, customer
Groups customerGroup = groupsC.getGroupByGroupId(new Integer(2));
List<Users> usersCollection = (List<Users>) customerGroup.getUsersCollection();
usersCollection.add(current);
//List<Groups> groupList = groupsC.getAllGroups();
customerGroup.setUsersCollection(usersCollection);
// Updating the group using GroupsController
groupsC.updateGroup(customerGroup);
//groupList.add(customerGroup);
//current.setGroupsCollection(groupList);
getFacade().create(current);
只有這樣,我怎麼得到的東西加入表(groups_has_user)是在同一時間到組表添加組,但再有就是對每一位用戶的自己的路線,我認爲這不是目的。許多人問過這個問題,但即使我讀了這些,我也無法知道。
謝謝抱歉! Sami