簡體   English   中英

在Java中的Collection中存儲數據庫數據(多對多關系)的最佳方法

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

我的問題在這里(可能是我的問題標題不正確)

我有三張桌子

  1. DATA (包含動作的外鍵和設備表)
  2. 行動
  3. 設備

一個DATA可以具有多個動作以及多個設備。

我已經緩存了所有行的DATA表。
現在, 我的目標是以一種可以通過特定的actionid和deviceid檢索DATA的方式進行存儲 就像查詢( select *from data where actionID=123 AND deviceId=456

我的方法是:使用Map<DEVICEID,Map<ACTIONID,DATAs>>進行存儲Map<DEVICEID,Map<ACTIONID,DATAs>>但是如何生成此地圖。 我上了三堂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
 }
}

在此先感謝您。如果有什么新方法,不勝感激。

當您始終按這兩個屬性搜索時,可以創建一個新類,將其DataIdentifier ,它由actionId和deviceId組成。 為了確保它可以用作HashMap<DataIdentifier, List<String>>

  1. 重寫public int hashCode()以返回從actionIddeviceId派生的哈希碼,
  2. 當actionId和deviceId相同時,重寫boolean equals(Object other)以返回true。

然后,您可以像這樣使用它:

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