Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist HashMap in ORMLite

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);
    }
    ... 
}
like image 438
fred Avatar asked Feb 02 '23 14:02

fred


1 Answers

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".

like image 183
Gray Avatar answered Feb 12 '23 09:02

Gray