三级分类查询也可以理解为递归查询,注意需要通过最顶层节点去递归其子类数据,通过父查询方法调用子查询方法,在子查询方法中递归查询所有子类,当判断没有子数据时便可结束当前递归查询操作。
如某物品类,其属性中仍然需要其子属性(若有)的当前类本身,即A类属性中包含A类,并且是个集合。
三级查询代码演示
(1)java代码演示
父类方法,也是方法的入口
子类方法,通过该方法递归出所有子类数据,直到最后的子类数据。
(2)python方法代码演示
#这段代码定义了一个 Python 类 CategoryEntity
,用于表示一个商品分类实体。类的构造函数 __init__
负责初始化实例的属性
class CategoryEntity:
def __init__(self, cat_id, name, parent_cid, children=None, cat_level=None, show_status=None, sort=None, icon=None,
product_unit=None, product_count=None):
self.cat_id = cat_id
self.name = name
self.parent_cid = parent_cid
self.children = children or []
self.cat_level = cat_level
self.show_status = show_status
self.sort = sort
self.icon = icon
self.product_unit = product_unit
self.product_count = product_count
def list_with_tree(entities):
# 获取所有数据,没有查询条件
# entities 是 CategoryEntity 对象的列表
# 做树形结构,分类
# 将集合的每一条数据,通过条件过滤
return list(filter(lambda category_entity: category_entity.parent_cid == 0, entities))
# 递归获取每一个菜单(当前菜单)的子分类
def get_children(entity, all_entities):
return [
CategoryEntity(
cat_id=category_entity.cat_id,
name=category_entity.name,
parent_cid=category_entity.parent_cid,
children=get_children(category_entity, all_entities),
cat_level=category_entity.cat_level,
show_status=category_entity.show_status,
sort=category_entity.sort,
icon=category_entity.icon,
product_unit=category_entity.product_unit,
product_count=category_entity.product_count
)
for category_entity in all_entities if category_entity.parent_cid == entity.cat_id
]
# 示例用法
entities = [
CategoryEntity(cat_id=1, name="Category 1", parent_cid=0, sort=2),
CategoryEntity(cat_id=2, name="Category 2", parent_cid=0, sort=1),
CategoryEntity(cat_id=3, name="Category 1.1", parent_cid=1, sort=2),
CategoryEntity(cat_id=4, name="Category 1.2", parent_cid=1, sort=1),
CategoryEntity(cat_id=5, name="Category 2.1", parent_cid=2, sort=3),
]
#列表推导(List Comprehension)的方式生成一个新的列表 result
,其中包含了通过遍历 list_with_tree(entities)
得到的每个 CategoryEntity
对象的新实例。
result = [
CategoryEntity(
cat_id=category_entity.cat_id,
name=category_entity.name,
parent_cid=category_entity.parent_cid,
children=get_children(category_entity, entities),
cat_level=category_entity.cat_level,
show_status=category_entity.show_status,
sort=category_entity.sort,
icon=category_entity.icon,
product_unit=category_entity.product_unit,
product_count=category_entity.product_count
)
for category_entity in list_with_tree(entities)
]
# 输出结果
for item in result:
print(f"Category: {item.name}, Sort: {item.sort}")
for child in item.children:
print(f" - Child: {child.name}, Sort: {child.sort}")
这个 Python 代码使用了列表推导和 Lambda 表达式,以及类的构造函数来模拟 Java 代码中的逻辑。请注意,Python 中没有像 Java 中的注解(@Data
、@TableName
等),因此你需要手动创建类并实例化对象。在示例中,使用了一个简化的 CategoryEntity
类和一些示例数据。你需要根据实际需要进行调整。
以上就是使用java和python进行三级递归查询的代码过程。