spring 多對多的保存



user和authority兩表經過中間表user_authority來實現關聯,user_authority表以下: java

在spring的domain的關聯代碼以下: spring

/**
  */
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(catalog = "xmgl", name = "user_authority", joinColumns = { @JoinColumn(name = "User_ID", referencedColumnName = "ID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "Authority_ID", referencedColumnName = "ID", nullable = false, updatable = false) })
@XmlElement(name = "", namespace = "")
java.util.Set<net.gvsun.domain.Authority> authorities; dom

在jsp頁面怎麼將權限傳到後來呢?經過先將數據保存到user中的另外一個字符串的對象,以下所示: jsp

<td class="label" valign="top">
          <fmt:message key="authority.cname.title"/>:
         </td>
    <c:forEach items="${authorities}" var="current" varStatus="i">
        <td >
                      <form:checkbox path="userName" value="${current.id}" />
      ${current.CName}
     </td>
    </c:forEach> fetch

我先將數據保存到user的userName中,而後經過userName傳到後臺的service層,而service層實現保存的方法以下: spa

/*
   * 保存新增的用戶權限
  */
public void saveAuthority(User user)
{
  String str = user.getUserName();
        String[] arrayStr = str.split(",");
        int id=user.getId();
        User user2=userDAO.findUserByPrimaryKey(id);
        Set<Authority> authorities=authorityDAO.findAllAuthoritys();
        Set<Authority> sets=user.getAuthorities();
        for(int i=0;i<arrayStr.length;i++){
             String auth=arrayStr[i];
         int authorityId=Integer.parseInt(auth);
         for(Authority authority:authorities)
         {
          if(authority.getId()==authorityId)
          {
           sets.add(authority);
          }
         }
         user2.setAuthorities(sets);
         userDAO.store(user2);
         userDAO.flush();
        } orm

} 對象

相關文章
相關標籤/搜索