Persist HashMap in ORMLite

眉间皱痕 提交于 2019-12-09 15:34:25

问题


Im using ORMLite in my Android app. I need to persist this class, which has a HashMap. What is a good way of persisting it? Its my first time trying to persist a HashMap, also first time with ORMLite so any advice would be greatly appreciated!

*Edit* If that makes any difference, the Exercise class is simply a String (that also works as id in the database), and the Set class has an int id (which is also id in database), int weight and int reps.

@DatabaseTable
public class Workout {

    @DatabaseField(generatedId = true)
    int id;

    @DatabaseField(canBeNull = false)
    Date created;

    /*
     * The hashmap needs to be persisted somehow
     */
    HashMap<Exercise, ArrayList<Set>> workoutMap;

    public Workout() {          
    }
    public Workout(HashMap<Exercise, ArrayList<Set>> workoutMap, Date created){
        this.workoutMap = workoutMap;
        this.created = created;
    }

    public void addExercise(Exercise e, ArrayList<Set> setList) {
        workoutMap.put(e, setList);
    }
    ... 
}

回答1:


Wow. Persisting a HashMap whose value is a List of Sets. Impressive.

So in ORMLite you can persist any Serializable field. Here's the documentation about the type and how you have to configure it:

http://ormlite.com/docs/serializable

So your field would look something like:

@DatabaseField(dataType = DataType.SERIALIZABLE)
Map<Exercise, List<Set>> workoutMap;

Please note that if the map is at all large then this will most likely not be very performant. Also, your Exercise class (and the List and Set classes) need to implement Serializable.

If you need to search this map, you might consider storing the values in the Set in another table in which case you might want to take a look at how ORMLite persists "foreign objects".



来源:https://stackoverflow.com/questions/7155923/persist-hashmap-in-ormlite

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