Issue
I need advice for my code simplification. I am using Struts 2, Spring, and Hibernate as framework.
File DAO:
public List<Model> getData() throws HibernateException {
List<Model> list = new ArrayList<Model>();
List<Object[]> res = new ArrayList<Object[]>();
String query = "SELECT table1.*, table2.* FROM table1, table2 WHERE table1.bridge_id = table2.bridge_id";
res = this.sessionFactory.getCurrentSession()
.createSQLQuery(query)
.list();
for (Object[] row : res) {
Model model = new Model();
model.setName((String) row[1]);
model.setDate((Date) row[2]);
list.add(model);
}
return list;
}
I try using
while(res.next()){ ... }
but next()
is not function in my project, like I am using size()
to count size of the list rather than length
of array.
for some reason I dont like to define function value in loop using row[0]
, what I want is to define the value as row["name"]
.
Solution
There was posible two ways to map column names to use with row data Object[]
which contains only values.
- Map column names to indeces.
Map<String, int> map = new HashMap<>()
map.put("name", 0);
map.put("date", 1);
for (Object[] row : res) {
Model model = new Model();
model.setName((String) row[map.get("name")]);
model.setDate((Date) row[map.get("date")]);
list.add(model);
}
- Map
Object[]
toMap<String, Object>
and use previous mapping
Map<String, int> map = new HashMap<>()
map.put("name", 0);
map.put("date", 1);
for (Object[] row : res) {
Model model = new Model();
Map<String, Object> map2 = new HashMap<>();
map2.put("name", row[map.get("name")]);
map2.put("date", row[map.get("date")]
model.setName((String) map2.get("name"));
model.setDate((Date) map2.get("date"));
list.add(model);
}
You can create an adapter class for row
which contains both mapping. The adapter takes Object[]
as a constructor parameter. Then use a function getValue(String)
which returns an Object
from the second map.
Answered By - Roman C
Answer Checked By - Robin (JavaFixing Admin)