Domanda

I need to query on my database (postgres) like this:
Entity:

class Cat{
  int id;
  String name;
}

main class:

int [] idCats = {1,2,7,5,8,4,9,10,12,14};

for(int id : idCats){ 
    Cat cat = session.load(Cat,id);
    (do something with cat, according your name)
}

But, this approach generates to many sqls. Considering i'll search almost all ids, there's a
way to bring all objects e search on it using criteria. Without implement by myself.

È stato utile?

Soluzione

You can use the second level cache feature of hibernate. But if your application is simple and you just want to fetch a cat with its id, then store the result of the query in a hashmap like

Map<Integer, Cat> mapCats = new HashMap<Integer, Cat>(); 

You can use the for loop to iterate over the list from DB.

Map<Integer, Cat> mapCats = new HashMap<Integer, Cat>();
for(Cat oneCat: listCats) { 
    mapCats.put(oneCat.id, oneCat);
}

Then retrieve using mapCats.get(catid);

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top