0

我有 3 个模型类,

User.java

public class UserData {
private Integer userID;
private String userName;
private String userPassword;
//getters and setters..

和权限类如..

Permission.java

public class PermissionsData {
private Integer permissionID;
private Integer userID;
private Integer moduleID;
private boolean permissionIsReadOnly;
private boolean permissionIsModify;
private boolean permissionIsFull;
//getters and setters

amd模块类,

module.java

public class ModuleData {
private Integer modId;
private String modName;

我的数据库中有一些模块。当我创建一个新用户时,我已经列出了这些模块并添加了复选框来设置权限。提交表单时,我需要将用户数据插入到用户表中,并将他对每个模块的权限插入到权限表中。

现在我只实现了向数据库插入角色..我的控制器就像..

@RequestMapping(value = "/addRole")
    public ModelAndView addNewRole()
    {
        ModelAndView mav = new ModelAndView("addNewRole");
        RoleData role = new RoleData();
        mav.getModelMap().put("roleDataObj", role);

        List<ModuleData> moduleList = moduleService.getAllModules();
        mav.getModelMap().addAttribute("ModuleList", moduleList);
        return mav;
    }

我怎样才能实现一次提交将数据添加到两个表?我还想知道模块和权限之间的映射我对今年春天和休眠真的很陌生。所以请用示例代码指导我。在此先感谢。

4

1 回答 1

2

如果您在映射中设置了级联

@Cascade(Cascade.all)
private List<Permission> permissions;

它很简单

public void saveNewUser(...)
{
    User user = new User();
    // fill properties
    Permission p = new Permission();
    // fill properties
    user.getPermissions().add(p);

    session.save(user);
}

更新:上面的代码可以使用类似的类结构。重要的部分是每个用户每个模块的权限集合/映射

public class Permission {
    private boolean IsReadOnly;
    private boolean IsModify;
    private boolean IsFull;
}

public class Module {
    private Integer id;
    private String name;
}

public class User {
    private Integer id;
    private String name;
    private String password;
    private Map<Module, Permission> permissions;
}

和映射

<class name="User">
  ...
  <map name="permissions" cascade="all">
    <key column="UserId"/>
    <index-many-to-many column="ModuleId" class="Module"/>
    <composite-element class="Permission">
      <property name="IsReadOnly"/>
      <property name="IsModify"/>
      <property name="IsFull"/>
    </composite-element>
  </map>
于 2012-05-25T06:01:21.640 回答