【问题标题】:Build Logic Tree like the where clause in sql像sql中的where子句一样构建逻辑树
【发布时间】:2020-05-12 05:57:32
【问题描述】:

我想用 Java 构建一个逻辑树,其中包含可以使用的条件 用于数据库插入。

例如:

Node tree = input0.eq(3).and(input1.eq(1).or(input2.greaterThan(5)));

可以转换为:

WHERE input0=3 AND (input1 = 1 OR input2 > 5)

由于一个节点可以是一个逻辑表达式,如和,或等,以及一个带有数据的叶子,我认为一个父节点类和两个子类是理想的。但我不知道如何处理嵌套表达式。我已经在这里阅读了一些类似的问题,但它们还不够具体。

public class Node {
    public Long id;

    public Node parent;
    public List<Node> children;
}
public class LogicalNode extends Node {
    LogicType logicType;
    public LogicalNode () {
        super();
    }
    getter and setter...
}
public class LeafNode extends Node {
    Object input;
    public LeafNode () {
        super();
    }
    getter and setter...
}
public enum LogicType 
{
   AND("and"),
   OR("or"),
   NOT("not"),
   EQ("="),
   GREATER_THAN(">"),
   LESSER_THAN("<");

    private String name;

    LogicType (String name) {
        this.name= name;
    }

    public String getName() {
        return name;
    }
}

【问题讨论】:

    标签: java data-structures tree logic where-clause


    【解决方案1】:

    为了让您开始,请尝试类似以下的操作:

    public abstract class Node {
       abstract void toSql();
    
       Node eq(Node other) { 
          return new LogicalNode(LogicalType.EQ, this, other);
       }
    
       ...
    }
    
    public class LeafNode extends Node {
        LeafNode(int value) { 
            this.value = value;
        }
    
        String toSql() {
            return this.value.toString();
        }
    }
    
    public class LogicalNode extends Node {
        LogicalNode(LogicalType type, Node left, Node right) { 
            this.logicalType = type;
            this.left = left;
            this.right = right;
        }
    
        String toSql() {
            return String.format(
                "(%s) %s (%s)",
                this.left.toSql(),
                this.logicalType.getName(),
                this.right.toSql()
            );
        }
    }
    

    这里的关键是LogicalNode 是使用另外两个Nodes 构造的,但它并不关心它们是LeafNodes 还是LogicalNodes。所有LogicalNode 知道的是,它有两个可以使用toSql 转换为字符串的东西。

    【讨论】:

    • 感谢您的建议,我仍然不确定如何实现 and,or,not,eq,greatherThan 和 lesserThan 方法。你有想法吗?这些方法需要返回一个节点,因为它们可以相互嵌套,如我的示例所示。
    • 在我的回答中为Node 类添加了更多详细信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多