Create multiple tables for one class in ORMLite

冷暖自知 提交于 2020-01-13 08:29:09

问题


I'm using ORMLite on Android and have the following question: Is it possible to create many tables based on a single Java class?

The tables should only differ in their names, and the access to them should be by name.

For example if I have a class:

public class Order{
    @DatabaseField
    public string Name;

    @DatabaseField
    public string Amount;
}

And I have a dynamic number of modules that can create orders. I want every module to have its own table, but all tables should have a similar schema.

I know I can add a field in the Order class that indicates the source module name, and have all the orders live in one table, but I was wondering if there's a way to separate the tables (for faster queries, faster deletion of orders from the same module and so on)

Thanks!


回答1:


The big question here is what do you mean by "dynamic". If you mean that you need to create these module Orders on the fly and you don't know their names beforehand then I believe a module-name field is the an efficient way to do this. To create a table for each type of order seems like premature optimization to me -- complexity without good reason.

That said, you can accomplish dynamic classes by instantiating a DatabaseTableConfig for each table and defining the class programmatically.

If you don't really mean dynamic, then the easiest way to accomplish putting each module Order in its own table would be with subclasses.

You could have:

@DatabaseTable
public class FooOrder extends Order {
    // fields will be gotten from Order
}

@DatabaseTable
public class BarOrder extends Order {
    // fields will be gotten from Order
}

The fields from Order will be in each of the fooorder and barorder tables.



来源:https://stackoverflow.com/questions/12038730/create-multiple-tables-for-one-class-in-ormlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!