How do you use ORMLite with an abstract class?

后端 未结 2 1654
后悔当初
后悔当初 2021-01-16 06:46

I have an base class Peripheral. Classes Sensor and Master are extensions of Peripheral. I need ORMlite to instantiate my

相关标签:
2条回答
  • 2021-01-16 07:20

    How can I have ORMlite load any Peripheral object since Peripheral is abstract?

    I think your problem stemmed from the fact that the @DatabaseTable needs to be on the Sensor and Master classes. It won't hurt it to also be on the base class but it won't be detected there.

    This will have one table named "Peripheral" used for both super-classes. Any fields (such as mSerial) from the base class will be detected and used as fields in both of the super-classes.

    The only limitation is that ORMLite is unable to differentiate between Sensor and Master. It right now is missing the feature which allows you to get all rows that are a Sensor and get all rows that are a Master. Also, it cannot generate the schema for them if the super-classes have their own fields marked with @DatabaseField.

    Edit:

    It's important to reiterate that ORMlite (as of 3/2013) does not support multiple sub-classes in the same table. Subclasses will inherit the database fields from the base class but they have to each be in their own table. Here's a discussion about this topic on the mailing list.

    To accomplish this, you could have 3 tables: 1 for the base class information and 2 for the sub-classes. The sub-class tables would have a foreign key to the associated base class row.

    0 讨论(0)
  • 2021-01-16 07:22

    Gray is correct, and I forgot about that reflection rule when I asked the question the first time. I have worked around the limitations on both limits of reflection and ORMlite not currently distiguishing between super classes. This is my structure:

    class Peripheral {
        @DatabaseField(generatedId)
        int _ID;
        @databaseField
        int serial;
        // ... Methods ommitted to be succint
    }
    
    class PeripheralWrapper extends Peripheral {
        final Peripheral mBase;
        PeripheralWrapper(Peripheral peripheral) {
            mBase = peripheral;
        }
        // ... Methods are overridden but call the base's methods instead
    }
    
    class Sensor extends PeripheralWrapper {
        Sensor(Peripheral peripheral) {
            super(peripheral);
        }
    }
    
    class Master extends PeripheralWrapper {
        Master(Peripheral peripheral) {
            super(peripheral);
        }
    }
    
    // This is the work around
    
    @DatabaseTable(tableName="Peripheral")
    class BasePeripheral extends Peripheral {
    }
    

    This work around is simple actually. Now I only inflate the basePeripheral and then pass those into the wrappers as needed. All inflation and delegation of wrapping is done in a PeripheralFactory.

    0 讨论(0)
提交回复
热议问题