bkmr_77,
I can't do this because this is not dynamic, if I pass another class model, like ProductModel, I wouldnt have the properties email, login, admin , etc.....
Understand?
I get what I want doing the following, but I'm fear that this isn't ok, because I make setString for all properties, even if they are Long or Date or what else.... But it works with Long, and I think it will work with other variable types too.
Anybody have any sugestion?
Code:
public static List search(AppModel appModel){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
String model = appModel.getClass().toString();
model = model.substring(model.lastIndexOf(".")+1);
StringBuilder sb = new StringBuilder()
.append(" from " ).append(model).append(" model ");
Map mapKeyValue = obterMapKeyValueBean(appModel);
Set setKeyValue = mapKeyValue.entrySet();
boolean whereUtilizado = false;
for (Iterator iter = setKeyValue.iterator(); iter.hasNext();) {
Entry entry = (Entry) iter.next();
if (!desprezarKey(entry.getKey()) && entry.getValue()!=null && !entry.getValue().equals("")){
if (!whereUtilizado){
sb.append(" where model.").append(entry.getKey()).append(" = :").append(entry.getKey());
whereUtilizado = true;
}
else{
sb.append(" AND model.").append(entry.getKey()).append(" = :").append(entry.getKey());
}
}
}
Query query = session.createQuery(sb.toString());
for (Iterator iter = setKeyValue.iterator(); iter.hasNext();) {
Entry entry = (Entry) iter.next();
if (!desprezarKey(entry.getKey()) && entry.getValue()!=null && !entry.getValue().equals("")){
query.setString((String)entry.getKey(), (String)entry.getValue());
}
}
return query.list();
}
private static Map obterMapKeyValueBean(AppModel appModel) {
BeanUtilsBean beanUB = BeanUtilsBean.getInstance();
Map mapProperties = null;
try {
mapProperties = beanUB.describe(appModel);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapProperties;
}
private static boolean desprezarKey(Object key) {
String chave = (String) key;
String[] desprezar = {"id", "versao", "class"};
for (int i = 0; i < desprezar.length; i++) {
if (chave.equals(desprezar[i])){
return true;
}
}
return false;
}