2012-04-04 25 views
1

Same question here, but it didn't help meJPA ManyToMany在用戶和組的情況下?

DB: users-table, groups and group_has_user

我有三個表和多對多的連接。在我的JSF應用程序中,我試圖添加用戶。在我的組表中有三個不同的組:管理員,客戶和用戶。

我做了什麼:

  1. 插入數據JSF型用戶點擊後保存。
  2. ManagedBean調用usersController從groupsController獲取組(customer-group)
  3. usersController ManagedBean創建新用戶並將其保存到mySQL-db。
  4. 問題是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

回答

1

我明白了。我的代碼很混亂,我把它清理出來並且幫助。我不太確定爲什麼更新groups-table會向Users-table插入一個新用戶,但對我來說可以。起初,我更新了groups-table並將用戶插入users-table,並且我總是得到一個例外,即已經有了pk(用戶名是pk)。所以它向用戶表做了兩個插入,但現在它工作得很好。沒有更多的線路組 - 表聯合表和用戶表。

// Add current new user to the customer-group 
      usersCollection.add(currentUser); 
      customerGroup.setUsersCollection(usersCollection); 

      // Updating the group using GroupsController, THIS INSERTS USER TO USERS-table as well!! 
      groupsC.updateGroup(customerGroup); 
相關問題