spring 多对多的保存



user和authority两表通过中间表user_authority来实现关联,user_authority表如下:

spring 多对多的保存_第1张图片

在spring的domain的关联代码如下:

/**
  */
@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;

在jsp页面怎么将权限传到后来呢?通过先将数据保存到user中的另一个字符串的对象,如下所示:

<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>

我先将数据保存到user的userName中,然后通过userName传到后台的service层,而service层实现保存的方法如下:

/*
   * 保存新增的用户权限
  */
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();
        }

}

 

你可能感兴趣的:(spring,中间表,保存,多对多)