1

在浏览 Hibernate Mapping 示例时,我发现,

当一个类包含 Collection 时,它在某处被声明为,

class Role{
  String roleName;
  Set<Permission> permissionName;
}

class Permission{
  String permissionName;
}

或者

class Role{
  String roleName;
}

class Permission{
  String permissionName;
}

class RolePermission{
  String roleName;
  String permissionName;
}

hbm.xml 文件在两种风格上都不同。

两者通用的数据库表

Role
-----
role_id(PK) role_name

Permission  
-----------
permission_id(PK) permission_name

Role_Permission
-----------------
role_permission_id   role_id(FK)    permission_id(FK)

应该使用哪种最佳方式,以及在生成的查询中考虑休眠模式会有什么不同。

4

2 回答 2

0

Go with the first in this case. Having a Role with a set of Permissions is the more natural way here. Because that's what your business problem is: You want roles with several permissions for each role. If it weren't for a relational database behind the application, you wouldn't even consider going with the second solution, it's a decomposition of the first class structure.

Generally this IS why you use ORMs (Hibernate here) so that you can have a more convenient class structure without having to worry how to decompose it to a relational database. So definitely go with the first one.

(What you'll lose: can't write querys easily for rolePermissions(but it's not a problem as it's just a "helper" class it doesn't model any real world thing))

于 2012-09-26T07:08:56.397 回答
0

I would use 1st way, because you will find difficulty with permissionName in both classes Permission and RolePermission as it is redundant in 2nd way :

class Role{
  private Integer id;
  private String roleName;
  private Set<Permission> permissionName;
  // getter setters and necessary methods
}

// use one to many relationship from Role to Permission 
class Permission{
  private Integer id;
  private String permissionName;
  // getter setters and necessary methods
}
于 2012-09-26T07:09:00.313 回答