简体   繁体   English

在Java中的Collection中存储数据库数据(多对多关系)的最佳方法

[英]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 ) DATA (包含动作的外键和设备表)
  2. ACTION 行动
  3. DEVICE 设备

one DATA can have multiple actions as well devices. 一个DATA可以具有多个动作以及多个设备。

I have cached DATA table with all rows. 我已经缓存了所有行的DATA表。
Now my target is to store in a way that I can retrieve DATA by particular actionid and deviceid. 现在, 我的目标是以一种可以通过特定的actionid和deviceid检索DATA的方式进行存储 Just like query ( select *from data where actionID=123 AND deviceId=456 ) 就像查询( 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. 我的方法是:使用Map<DEVICEID,Map<ACTIONID,DATAs>>进行存储Map<DEVICEID,Map<ACTIONID,DATAs>>但是如何生成此地图。 I have three pojo class: 我上了三堂pojo课:

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. 当您始终按这两个属性搜索时,可以创建一个新类,将其DataIdentifier ,它由actionId和deviceId组成。 To make sure it can be used as a key in a HashMap<DataIdentifier, List<String>> : 为了确保它可以用作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 重写public int hashCode()以返回从actionIddeviceId派生的哈希码,
  2. override boolean equals(Object other) to return true when both actionId and deviceId are the same. 当actionId和deviceId相同时,重写boolean equals(Object other)以返回true。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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