我想在Java中建立一个逻辑树,其中包含可以用于数据库插入的条件。
例如,我想在Java中建立一个逻辑树,其中包含了可以用于数据库插入的条件。
Node tree = input0.eq(3).and(input1.eq(1).or(input2.greaterThan(5)));
可以转换为:
WHERE input0=3 AND (input1 = 1 OR input2 > 5)
由于一个Node可以是一个逻辑表达式,如and,or等,也可以是一个包含数据的Leaf,我想一个父Node类和两个子类,将是理想的。但我不知道如何处理嵌套表达式。我已经在这里读到过一些类似的问题,但其实不够具体。
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;
}
}
为了让你入门,可以尝试类似于这样的东西。
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
是用另外两个 Node
但它并不关心它们是否是。LeafNode
或 LogicalNode
s. 所有 LogicalNode
知道的是,它有两样东西,可以用 toSql
.