I have a behavior tree with different leaf nodes that execute tasks. When building out the tree relationship in the database I need an association between the leaf node entry and the Java class that will actually perform the task execution. I’ve seen some examples that store the canonical name of the Java task class with the leaf node data, and then instantiate the class at runtime using reflection. I’m not sure I like that approach, but I’m looking for all of the alternatives so I can make an informed decision.
You can use JPA with inheritance.
There are several variations (“patterns”):
-
all objects share the same table and there is a “discriminant” column/attribute (this is the closest to the one you explain). It is quick for queries, but you will have a column for each attribute of a subclass (if you have 20.000 instances, and only two instances of a subclass that defines attribute “x”, you will have 20.000 rows where attribute ‘x’ is implemented as a null column. And it is more difficult to enforce that, when the instance is of the given subclass, the attribute may not be null (you would require a programmed constraint).
-
each subclass has a different subclass (good if subclasses have lots of different attributes, but implies joins when querying the DB).
-
one table is used for common attributes, there are tables for attributes specific to subclasses (this is a hybrid of the other two).
The advantage is that it is standard, and you forget about how to persist/retrieve the data, the JPA already does it for you.
The disavantage is that it is a full API and you should learn how it does manage relationships(including cascading and/or lazy loading), JPQL/Criteria, etc.
4