简体   繁体   中英

Best way to store Database Data(many to many relation) in Collection in java

My Problem is Here (May be my question title is not proper)

I have Three table

  1. DATA (which contain foreign key of action and device table )
  2. ACTION
  3. DEVICE

one DATA can have multiple actions as well devices.

I have cached DATA table with all rows.
Now my target is to store in a way that I can retrieve DATA by particular actionid and deviceid. Just like query ( select *from data where actionID=123 AND deviceId=456 )

My approach is to take : to store using Map<DEVICEID,Map<ACTIONID,DATAs>> but how to generate this map. I have three pojo class:

public class DATA {
int dataId;
int actionId;
int deviceId;
String dataDetail;
}

public class Action {
int actionId;
int acttionName;
}

public class Device {
int deviceId;
String deviceName;
}

public class GenerateObject {
static List<DEVICE> devices = new ArrayList<DEVICE>();
static List<Action> actions= new ArrayList();
static List<DATA> datas = new ArrayList();
public static void generateCollection(){
    Map<String,Map<String,List>> dataMap = new HashMap<String, Map<String,List>>();
    //Write Code which set dataMap
 }
}

Thanks in advance.If any new approach is their than that would be apreciated.

When you always search by these two attributes, you could create a new class, lets call it DataIdentifier , which consists of both actionId and deviceId. To make sure it can be used as a key in a HashMap<DataIdentifier, List<String>> :

  1. override public int hashCode() to return a hash code which is derived from both the actionId and the deviceId and
  2. override boolean equals(Object other) to return true when both actionId and deviceId are the same.

You would then use it like this:

List<String> dataDetails = datas.find(new DataIdentifier(actionId, deviceId));
Map<String,Map<String,List>> datas = new HashMap<String, Map<String,List>>();
Map<String,List<T>> actionMap = new HashMap<String, List<T>>;
actionMap.put("actionID", Arrays.asList(1,2)); // assuming T = Integer
datas.put("deviceID", actionMap);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM