2012-04-04 10 views
1

Same question here, but it didn't help meJPA ManyToManyユーザーとグループの場合

DB: users-table, groups and group_has_user

私は3つのテーブルを持って、多くの接続には多くました。私のJSFアプリケーションでは、ユーザーを追加しようとしています。私のグループには、管理者、顧客、ユーザーの3つのグループがあります。

  1. をユーザーがクリックして保存JSFフォームにデータを挿入した後:私が行っている何

  2. usersControllerという名前のManagedBeanは、グループ(顧客グループ)をgroupsから削除します。
  3. usersController ManagedBeanは新しいユーザーを作成し、mySQL-dbに保存します。

    public class Users implements Serializable { 
    @ManyToMany(mappedBy = "usersCollection") 
    private Collection<Groups> groupsCollection; 
    

    グループ:

  4. 問題はそのgroups_has_userテーブルが空

とコード

ユーザーである

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; 

がUserController-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)を得た方法グループテーブルに同時にグループを追加することですが、その後、すべてのユーザーのための独自の行があると私はそれが目的ではないと思います。多くの人がそれを聞いてきましたが、それを読んでもわかりませんでした。

ありがとうございます! サミ

答えて

1

私はそれを働かせました。私のコードは乱雑で、私はそれをきれいにして助けました。グループテーブルを更新して新しいユーザーをUsers-tableに挿入する理由はわかりませんが、私にとっては大丈夫です。最初はgroups-tableとinserted userをusers-tableに更新しました。私はいつもpkが存在するという例外があります(usernameはpkです)。だから、それはユーザーテーブルに2つの挿入を行いましたが、今は完全に動作しています。グループへの行はこれ以上なく、ジョイントテーブルとユーザーテーブルだけになります。

// 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); 
関連する問題