RuoYi Entity Base Classes: BaseEntity Audit Fields & TreeEntity Inheritance Design
This article analyzes RuoYi 3.9.2's BaseEntity and TreeEntity base classes, showing how audit fields, a dynamic params Map, and tree-specific fields are consolidated to eliminate boilerplate across hundreds of entities, with concrete MyBatis mapper examples and design trade-off discussions.
BaseEntity: Consolidating Audit Fields
RuoYi places BaseEntity in com.ruoyi.common.core.domain. Core entities like SysUser, SysDept, SysRole extend it directly:
public class SysUser extends BaseEntity { }BaseEntityimplements Serializable and declares serialVersionUID as a defensive convention — RuoYi uses JSON (Jackson/FastJson2) for serialization, not Java native binary serialization, but the interface prevents NotSerializableException if any code path accidentally uses native serialization.
Fields
/** Search value */
@JsonIgnore
private String searchValue;
/** Creator */
private String createBy;
/** Create time */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/** Updater */
private String updateBy;
/** Update time */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/** Remark */
private String remark;
/** Request parameters */
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Map<String, Object> params;Five audit fields ( createBy, createTime, updateBy, updateTime, remark) map 1:1 to database columns create_by, create_time, update_by, update_time, remark. New business tables only need these five columns; entities inherit them automatically. searchValue and params are framework-level carriers with no database columns.
Three Jackson Annotations
@JsonIgnoreon searchValue: excludes from both serialization and deserialization — responses never contain it, JSON request bodies never bind it. However, GET query parameters like ?searchValue=xxx still bind via Spring MVC form binding. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") on createTime / updateTime: fixes date serialization format. Without it, Jackson defaults to timestamps or ISO-8601 strings, which frontends cannot display directly. @JsonInclude(JsonInclude.Include.NON_EMPTY) on params: only outputs when non-null and non-empty. Most requests don't use params; without this, responses would contain "params":{} noise everywhere.
searchValue: Reserved Keyword Search Slot
@JsonIgnoreonly affects Jackson; GET ?searchValue=xxx still binds to the entity field via Spring MVC. The field is designed as a universal keyword search slot for list queries.
Example from SysNoticeController querying read users with fuzzy match on username/nickname:
public TableDataInfo readUsersList(Long noticeId, String searchValue) {
startPage();
List<?> list = noticeReadService.selectReadUsersByNoticeId(noticeId, searchValue);
return getDataTable(list);
}Corresponding XML uses searchValue in LIKE:
<if test="searchValue != null and searchValue != ''">
and (
u.user_name like concat('%', #{searchValue}, '%')
or u.nick_name like concat('%', #{searchValue}, '%')
)
</if>If using BaseEntity.searchValue, entities inherit the field automatically; frontends send ?searchValue=xxx, XML references #{searchValue}, eliminating per-interface search parameter declarations.
params: Universal Runtime Parameter Bag
paramsis a Map<String, Object> with lazy-initialization getter:
public Map<String, Object> getParams() {
if (params == null) {
params = new HashMap<>();
}
return params;
}This guarantees non-null Map for Spring MVC binding (e.g., params[beginTime]=2024-01-01 calls getParams().put(...)).
Three usage categories, each with real framework locations:
Time range queries : Spring MVC auto-binds request params; XML accesses #{params.beginTime} / #{params.endTime} Data permissions : @DataScope aspect writes permission SQL; XML uses ${params.dataScope} (string concat, not #{})
Service-to-mapper extension params : Service actively put s values; XML reads #{params.userId} etc.
Time range example: SysUserMapper.xml filters by create_time:
<if test="params.beginTime != null and params.beginTime != ''">
AND date_format(u.create_time,'%Y%m%d') >= date_format(#{params.beginTime},'%Y%m%d')
</if>
<if test="params.endTime != null and params.endTime != ''">
AND date_format(u.create_time,'%Y%m%d') <= date_format(#{params.endTime},'%Y%m%d')
</if>No entity declares beginTime / endTime; full-repo search for getParams().put shows only data-scope aspect and menu service write to params, proving beginTime / endTime come solely from request binding.
Data permission example: DataScopeAspect computes WHERE clause from user roles, writes to params:
baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");XML uses ${params.dataScope} (string interpolation) to embed the SQL fragment. Security: since params accepts front-end binding, a malicious params[dataScope]=... could inject SQL. The aspect first clears then recomputes:
clearDataScope(point); // wipe any injected dataScope
handleDataScope(point, ...); // write genuine permission SQLExtension param example: SysMenuServiceImpl.selectMenuList passes current userId for non-admin filtering:
menu.getParams().put("userId", userId);
menuList = menuMapper.selectMenuListByUserId(menu);Mapper reads #{params.userId}. No entity field or method signature changes needed.
Core design: business fields stay strongly typed on the class; runtime query/permission params live in params — flexible, zero-cost extension. Boundary is clear: params bypasses compile-time checks, especially ${params.dataScope} string concat, so the aspect must clear-before-write to prevent injection.
TreeEntity: Second-Layer Tree Extraction
TreeEntityextends BaseEntity, adding tree-specific fields:
/** Parent menu name */
private String parentName;
/** Parent menu ID */
private Long parentId;
/** Display order */
private Integer orderNum;
/** Ancestor list */
private String ancestors;
/** Child departments */
private List<?> children = new ArrayList<>();parentIdpoints to immediate parent; ancestors is comma-separated full path (e.g., 0,100,101); orderNum controls sibling ordering; children holds child nodes; parentName redundantly stores parent name for frontend display. ancestors enables descendant queries without recursion: MySQL find_in_set finds all descendants in one query. SysDeptMapper example:
select * from sys_dept where find_in_set(#{deptId}, ancestors)Why find_in_set not LIKE? LIKE '%100%' matches 0,1000, (substring), while find_in_set(100, ancestors) matches only when 100 is a complete comma-delimited element — precise.
children's List<?> Problem
childrendeclared as List<?> wildcard — a read-only view. add fails compilation: children.add(new SysDept(...)) won't compile. Tree building requires recursive add, forcing unchecked casts that defeat compile-time safety.
Concrete tree entities need different types: SysDept needs List<SysDept>, SysMenu needs List<SysMenu>. Base class cannot know. Hence framework's own core trees SysDept and SysMenu extend BaseEntity directly and declare strong-typed children:
public class SysDept extends BaseEntity {
private Long parentId;
private String ancestors;
private Integer orderNum;
private String parentName;
private List<SysDept> children = new ArrayList<SysDept>(); // strong type
// ...
}SysMenusimilarly declares List<SysMenu> children. Hand-written core trees skip TreeEntity for type safety and simpler recursive building.
TreeEntity's Real Consumer: Code Generator
TreeEntityis unused in framework core business code. The code generator uses it: when generating CRUD for a table marked as "tree table" (has parent_id etc.), the Velocity template sets base class to TreeEntity:
#if($table.crud || $table.sub)
#set($Entity="BaseEntity") ## normal table -> BaseEntity
#elseif($table.tree)
#set($Entity="TreeEntity") ## tree table -> TreeEntity
#end
public class ${ClassName} extends ${Entity}Generator's GenTableColumn.isSuperColumn lists both base classes' fields to avoid duplicate generation:
public static boolean isSuperColumn(String javaField) {
return StringUtils.equalsAnyIgnoreCase(javaField,
// BaseEntity
"createBy", "createTime", "updateBy", "updateTime", "remark",
// TreeEntity
"parentName", "parentId", "orderNum", "ancestors");
}Thus TreeEntity is a ready-made base for generated simple tree tables; complex core trees use strong-typed fields directly.
Design Reflections
Inheritance Benefit vs Cost
BaseEntityeliminates duplicate audit field declarations across dozens/hundreds of entities. Combined with mapper's uniform #{createBy} access, new entities gain full audit capability at near-zero cost. Cost: Java single inheritance — entities consume their only extends slot. RuoYi judges entities rarely need a second business base class; if they do, composition or code generation must fill the gap.
Why Primary Key Not in BaseEntity
BaseEntitycollects fields present in all tables with unified framework handling: audit fields written by service, params read/written by aspects and MVC. Primary keys don't belong: RuoYi convention is tablePrefix + Id (e.g., SysUser.userId → user_id, SysDept.deptId → dept_id). Names and types differ per table; MyBatis binds by property name. A base id field would coexist with child's own PK, causing confusion. Only classes like TreeSelect (frontend tree component convention) declare a generic id themselves.
params Separates Runtime Params from Business Fields
beginTime, dataScope, userId share two traits: not business fields, yet must reach SQL. Instead of per-field declarations or signature changes, a single Map in the base class serves as universal exit: business fields strongly typed & validated; runtime params weakly typed but zero-cost extensible. Boundary is sharp — params bypasses compile checks, especially ${params.dataScope} string concat, so the aspect must clear-then-recompute to avoid becoming a SQL injection vector.
List<?> Lesson
TreeEntityused List<?> to accommodate all tree subclasses, but the result is neither add -able nor type-safe — core entities SysDept / SysMenu reject it and declare their own fields. Proper approach: make TreeEntity generic TreeEntity<T> with List<T> getChildren(), letting subclasses bind their own type. A base class sacrificing type info for generality loses its users — generated simple trees tolerate it; complex trees need strong typing.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
