Organisational Structure and Personnel Management
Introduction
"Organisational Structure and Personnel Management" is a question that is repeatedly asked in interviews and real-world scenarios. Let's start with the conclusion.
The organisational structure is the backbone of the OA system: permissions, document circulation, and meeting room requests all depend on "who belongs to which department". This article explains how to store, query, and display tree structures, as well as the relationship between personnel and login accounts.
I. Domain Model
1.1 Organisation
/**
* @hibernate.class table="T_Organization"
*/
public class Organization {
/** @hibernate.id generator-class="native" */
private int id;
private String name; // 机构名称
private String sn; // 路径标识,如 1_3_7
private String description; // 描述
private Organization parent; // 父机构(顶级机构为 null)
private Set children; // 子机构集合
}
Mapping key points:
<class table="T_Organization" name="com.oa.model.Organization">
<id name="id"><generator class="native"/></id>
<property name="name"/>
<property name="sn"/>
<property name="description"/>
<many-to-one column="pid" name="parent"/>
<set lazy="false" inverse="true" name="children">
<key column="pid"/>
<one-to-many class="com.oa.model.Organization"/>
</set>
</class>
many-to-oneuses thepidcolumn for self-association to form a tree;- Set
childrentolazy="false", because the organisation tree needs to be recursively rendered on the page (used in conjunction with OpenSessionInView); inverse="true"Give the right to maintain the foreign key to the "many" side to avoid unnecessary updates.
1.2 Person and User
public class Person {
private int id;
private String name; // 姓名
private String sex; // 性别
private String address; // 住址
private String duty; // 职务
private String phone; // 电话
private String description;
private Organization org; // 所属机构(多对一)
private User user; // 对应的登录账号(一对一)
}
public class User {
private int id;
private String username; // 登录名
private String password; // 密码(明文存储,示例项目未加密)
private Date createTime; // 账号创建时间
private Date expireTime; // 账号失效时间
private Person person; // 对应人员
}
**Why split into Person and User? ** Because the lifecycles of "Person" and "Account" are different:
- A Person may not have an account (e.g., an external contact in the address book);
- Accounts have independent activation/deactivation times;
- The subject of the authorisation system (ACL) is
User(principalType="User"), whilePersonis used when displaying personnel information.
II. Implementation of the Organisation Tree
2.1 Two query perspectives
public PagerModel findOrgs(int parentId) {
// parentId == 0 表示查顶级机构
if (parentId == 0) {
return searchPaginated("from Organization o where o.parent is null");
}
return searchPaginated("from Organization o where o.parent.id = ?", parentId);
}
This is called drill-down by level (lazy-loaded tree): The page only displays the current level at a time, and when a node is clicked, parentId is passed back to query the next level. The advantage is that the amount of data can be controlled, and the disadvantage is that continuous requests are required for interaction.
The other way is to use the sn prefix to query the entire subtree at once:
-- 查 id=3 的机构及其所有后代
SELECT * FROM T_Organization WHERE sn LIKE '1_3%' ORDER BY sn;
2.2 Adding organisations and sn calculation
sn is the "ID path from the root to the current node". When adding, you must first save get the auto-incrementing ID, and then backfill sn:
public void addOrg(Organization org, int parentId) {
if (parentId != 0) {
org.setParent((Organization) getHibernateTemplate().load(Organization.class, parentId));
}
getHibernateTemplate().save(org); // 先保存,生成 id
org.setSn(org.getParent() == null
? ("" + org.getId()) // 顶级:sn = "1"
: (org.getParent().getSn() + "_" + org.getId())); // 子级:sn = "1_3"
getHibernateTemplate().update(org); // 再更新 sn
}
| id | name | pid | sn |
|---|---|---|---|
| 1 | Head Office | NULL | 1 |
| 3 | R&D Department | 1 | 1_3 |
| 7 | Group 1 | 3 | 1_3_7 |
With sn, you can get the entire ancestor chain or the entire subtree with a single SQL query, without the need for recursive queries.
2.3 Security checks for deleting organisations
public void delOrg(int orgId) {
Organization org = (Organization) getHibernateTemplate().load(Organization.class, orgId);
// 存在子机构则不允许删除
if (org.getChildren().size() > 0) {
throw new SystemException("存在子机构,不允许删除", "exception.org.del", org.getId());
}
getHibernateTemplate().delete(org);
}
In a real project, two additional checks are required: Whether there are still personnel under the organisation and Whether the organisation has been referenced by authorised records. Otherwise, dirty data will be generated after deletion.
2.4 Modifying an organisation
public void updateOrg(Organization org, int parentId) {
if (parentId != 0) {
org.setParent((Organization) getHibernateTemplate().load(Organization.class, parentId));
}
getHibernateTemplate().update(org);
}
Note: Once "Move Organisation" (change parent node) is allowed,
snmust be recalculated simultaneously for that node and all its descendants, otherwisesnwill become invalid. The sample project does not implement the move function, and a recursive update needs to be added in actual development.
3. Page Display: Dojo Tree + Freemarker Recursive Template
3.1 Recursive template
The organisation tree is rendered using Freemarker, and the trick is that the template contains itself:
tree.ftl (Outer layer, constructs the Dojo control container):
<div dojoType="TreeBasicController" widgetId="treeController"></div>
<div dojoType="TreeSelector" widgetId="treeSelector" eventNames="select:nodeSelected"></div>
<div dojoType="Tree" selector="treeSelector">
<#list orgs as org>
<#include "tree_node.ftl">
</#list>
</div>
tree_node.ftl (Recursive body):
<div dojoType="TreeNode" title="${org.name}" objectId="${org.id}">
<#list org.children as org>
<#include "tree_node.ftl">
</#list>
</div>
<#list org.children as org> Shadow the outer variable org as a child node, then <#include> itself, and recursion of any depth is completed.
3.2 Wrapping with EL functions
In order to output the entire tree in a single line in JSP, encapsulate it as a custom EL function:
public class OrgTreeFunction {
public static String tree(List orgs) {
try {
Configuration cfg = FreemarkerManager.getConfiguration();
Template template = cfg.getTemplate("tree.ftl");
Writer out = new StringWriter();
Map rootMap = new HashMap();
rootMap.put("orgs", orgs);
template.process(rootMap, out);
return out.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Declare in my.tld:
<function>
<name>orgTree</name>
<function-class>com.oa.web.OrgTreeFunction</function-class>
<function-signature>java.lang.String tree(java.util.List)</function-signature>
</function>
Use in JSP:
<%@ taglib prefix="my" uri="http://www.example.com/oa/functions" %>
${my:orgTree(orgs)}
Recursively rendering the entire tree can be very slow when there are a large number of organisations. In real projects, it is recommended to retain lazy loading (clicking on a node to query its child nodes) or to add caching.
IV. Personnel Management
The structure of the personnel module is completely symmetrical with that of the organisation module, making it the best example for practising the "module development approach":
| Level | Organisation | Personnel |
|---|---|---|
| Entity | Organization |
Person |
| Interface | OrgManager |
PersonManager |
| Implementation | OrgManagerImpl |
PersonManagerImpl |
| ActionForm | OrgActionForm |
PersonActionForm |
| Action | OrgAction |
PersonAction |
| JSP | WebRoot/org/* |
WebRoot/person/* |
The special feature of a person is that it needs to be associated with two objects:
public void addPerson(Person person, int orgId) {
person.setOrg((Organization) getHibernateTemplate().load(Organization.class, orgId));
getHibernateTemplate().save(person);
}
And assigning accounts to personnel in user management (one Person corresponds to 0 or 1 User).
5. How to write an Action: DispatchAction handles all create, delete, update and query operations
Taking organisations as an example, one Action carries all operations and uses the method parameter for dispatch:
public class OrgAction extends BaseAction {
private OrgManager orgManager;
public void setOrgManager(OrgManager orgManager) { this.orgManager = orgManager; }
/** 未指定 method 时默认执行,显示机构列表 */
@Override
protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
int parentId = ((OrgActionForm) form).getParentId();
request.setAttribute("pm", orgManager.findOrgs(parentId));
return mapping.findForward("index");
}
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
OrgActionForm oaf = (OrgActionForm) form;
Organization org = new Organization();
BeanUtils.copyProperties(org, oaf);
orgManager.addOrg(org, oaf.getParentId());
return mapping.findForward("pub_add_success");
}
public ActionForward del(...) { orgManager.delOrg(oaf.getId()); return mapping.findForward("pub_del_success"); }
public ActionForward update(...) { ... }
}
Access method:
/org.do → 列表(unspecified)
/org.do?method=add → 新增
/org.do?method=del&id=7 → 删除
/org.do?parentId=3 → 查看 id=3 的子机构
VI. Recommended Development Order
Developing a module in this order will almost certainly avoid detours:
- Familiarise yourself with the requirements – The organisation must support unlimited levels, top-level organisations, and deletion protection;
- Establish a domain model – Draw the fields and self-associations of
Organization; - Write entity classes and add XDoclet annotations —— Run Ant to generate mappings;
- Table creation and verification —— Start Tomcat to see if the DDL meets expectations;
- Design business interfaces based on use cases ——
addOrg / delOrg / updateOrg / findOrg / findOrgs; - Implement the interface and validate it with JUnit —— Run it once with
OrgManagerTest; - Design the page flow – List → Add → Success prompt;
- Write Action/ActionForm/JSP – Follow the DispatchAction template above;
- Complete step by step – Validation, pagination, tree view.
This process will be used repeatedly in the Permissions, Official Documents, and Meeting Rooms modules.
Summary of Key Points
- The structure of the Personnel module and the Organisation module are completely symmetrical, making them the best examples for practising the "module development approach": | Layer | Organisation | Personnel | |---|---|---| | Entity |
Organization… - Taking the organisation module as an example, one Action carries all operations and uses the
methodparameter for distribution: ```java public class OrgAction extends BaseAct… -
- Table creation verification – Start Tomcat to see if the DDL meets expectations
- Developing a module in this order almost guarantees a smooth process: 1. Familiarise yourself with the requirements – Organisations must support unlimited levels, top-level organisations, and deletion protection
由站内小编编辑整理