有没有办法一次性持久化具有多个映射元素的实体?

huangapple 未分类评论47阅读模式
英文:

Is there any way to persist the entity having multiple map elements at one go?

问题

我正在尝试找到减少代码重复的方法。就像我在这个类中有多个 Map 元素一样。如果您有什么建议,请告诉我..!

public Class MyObject{
private Map map1;
private Map map2;
private Map map3;

//有setter/getter方法
}

importDatabase(){
//这里我有map1、map2、map3元素中的数据
 importMap(MyObject.getMap1());
importMap(MyObject.getMap2());
importMap(MyObject.getMap3());
}

importMap(Map map){
//希望将map对象一次性插入数据库,而不是为每种类型创建3个方法
Iterator iterator = map.values().iterator;
while(iterator.hasNext(){
}
}
英文:

I am trying to find ways to reduce the code repetition. Like this code I have multiple Map elements in my class. Please suggest me if you have something..!

public Class MyObject{
private Map map1;
private Map map2;
private Map map3;

//having setter/getter
}

importDatabase(){
//here i have data in the map1, map2, map3 elements
 importMap(MyObject.getMap1());
importMap(MyObject.getMap2());
importMap(MyObject.getMap3());
}

importMap(Map map){
//want to insert map objects into database at one go, instead of creating 3 methods for each type
Iterator iterator = map.values().iterator;
while(iterator.hasNext(){
}
}

答案1

得分: 0

如果您拥有许多相似的同类型对象(在您的情况下是“地图”),并且对它们都执行相同的操作(将它们放入数据库),一种简单且通常可行的避免重复的方法是将它们存储在一个数组ArrayList中(如果您事先不知道它们的数量),然后在for循环或foreach循环中执行操作。

对于三个元素,这并不总是值得的,实际上可能会使代码比以前更难读懂。这只会使您的代码变得更短,而不会改善性能(我假设这就是您所说的“一次性”)。

英文:

If you have many similar object of the same type (maps in your case) and perform the same operations on all of them (put them in a database), a simple and usually viable way to avoid repetition is to store them in an array or in an ArrayList (if you don't know how many they are in advance) and perform the operations in a for or foreach loop.

With three elements it isn't always worth the effort and can actually make the code less readable than before. This will only make your code shorter and not improve performance (I assumed this is what you meant with at one go).

huangapple
  • 本文由 发表于 2020年6月5日 23:45:48
  • 转载请务必保留本文链接:https://java.coder-hub.com/62219231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定