View Javadoc

1   package comum.database;
2   
3   import java.io.Serializable;
4   import java.lang.reflect.InvocationTargetException;
5   import java.lang.reflect.Method;
6   import java.util.ArrayList;
7   import java.util.Collection;
8   import java.util.Iterator;
9   import java.util.List;
10  import java.util.Set;
11  
12  import javax.servlet.http.HttpServletRequest;
13  
14  import org.apache.log4j.Logger;
15  import org.hibernate.Criteria;
16  import org.hibernate.HibernateException;
17  import org.hibernate.ObjectNotFoundException;
18  import org.hibernate.Session;
19  import org.hibernate.Transaction;
20  import org.hibernate.criterion.Criterion;
21  import org.hibernate.criterion.Expression;
22  import org.hibernate.criterion.Order;
23  
24  import comum.util.Data;
25  import comum.util.LogBean;
26  import comum.util.Util;
27  
28  import ecar.exception.ECARException;
29  import ecar.login.SegurancaECAR;
30  import ecar.pojo.PaiFilho;
31  
32  /**
33   * Classe para extensão das classes do tipo DAO.<BR>
34   * Implementa as características básicas de manutenção de objetos utilizando
35   * Hibernate.<BR>
36   * Pode ser estendida para classes xxxxDao onde xxxx é o nome da classe que
37   * precisa implementar métodos mais específicos.
38   */
39  public class Dao {
40  
41  	/* constantes para ordenacao */
42  	public static final String ORDEM_ASC = "asc";
43  	public static final String ORDEM_DESC = "desc";
44  	protected Logger logger = null;
45  	protected Logger loggerAuditoria = null;
46  	protected LogBean logBean = null;
47  
48  	/* objeto de sessao */
49  	protected Session session;
50  
51  	protected HttpServletRequest request = null;
52  
53  	/**
54  	 * Construtor Dao.<br>
55  	 * Tenta abrir uma conexão com o banco de dados pela SessionFactory do
56  	 * Hibernate.<br>
57  	 * 
58  	 * @author N/C
59  	 * @since N/C
60  	 * @version N/C
61  	 */
62  	public Dao() {
63  		try {
64  			session = HibernateUtil.currentSession();
65  			logger = Logger.getLogger(this.getClass());
66  		} catch (Throwable t) {
67  			t.printStackTrace();
68  			logger
69  					.fatal("Não foi possível inicializar uma sessão do hibernate adequadamente. Verifique e corrija o erro acima.");
70  		}
71  	}
72  
73  	/**
74  	 * Retorna a sessão corrente.<br>
75  	 * 
76  	 * @author N/C
77  	 * @since N/C
78  	 * @version N/C
79  	 * @return Session
80  	 */
81  	public Session getSession() {
82  		return session;
83  	}
84  
85  	/**
86  	 * Atualiza a sessão corrente com uma nova sessão.<br>
87  	 * 
88  	 * @author N/C
89  	 * @since N/C
90  	 * @version N/C
91  	 * @param Session
92  	 *            session
93  	 */
94  	public void setSession(Session session) {
95  		this.session = session;
96  	}
97  
98  	/**
99  	 * Devolve o tamanho de uma collection sem inicializá-la.<br>
100 	 * 
101 	 * @author N/C
102 	 * @since N/C
103 	 * @version N/C
104 	 * @param Collection
105 	 *            col
106 	 * @return int
107 	 * @throws ECARException
108 	 */
109 	@SuppressWarnings("unchecked")
110 	public int contar(Collection col) throws ECARException {
111 		try {
112 			return ((Integer) session.createFilter(col, "select count(*)")
113 					.iterate().next()).intValue();
114 		} catch (HibernateException e) {
115 			this.logger.error(e);
116 			throw new ECARException("erro.hibernateException");
117 		}
118 	}
119 
120 	/**
121 	 * @author wanessa.terasawa
122 	 * @since implementado deviado a erro na exclusão de Tipo de Acompanhamento
123 	 * @version v01 em 20.11.2009
124 	 * @param Collection
125 	 *            col
126 	 * @return long
127 	 * @throws ECARException
128 	 */
129 	public long contarLong(Collection col) throws ECARException {
130 		try {
131 			return ((Long) session.createFilter(col, "select count(*)")
132 					.iterate().next()).longValue();
133 		} catch (HibernateException e) {
134 			this.logger.error(e);
135 			throw new ECARException("erro.hibernateException");
136 		}
137 	}
138 
139 	/**
140 	 * Insere um objeto utilizando uma transação do Hibernate.<br>
141 	 * 
142 	 * @author N/C
143 	 * @since N/C
144 	 * @version N/C
145 	 * @param Object
146 	 *            obj
147 	 * @throws ECARException
148 	 *             - executa o rollback da transação e dispara e exception
149 	 */
150 	public void salvar(Object obj) throws ECARException {
151 		inicializarLogBean();
152 		Transaction tx = null;
153 		try {
154 			tx = session.beginTransaction();
155 			session.save(obj);
156 			tx.commit();
157 			if (logBean != null) {
158 				logBean.setCodigoTransacao(Data.getHoraAtual(false));
159 				logBean.setObj(obj);
160 				logBean.setOperacao("INC");
161 				loggerAuditoria.info(logBean.toString());
162 			}
163 		} catch (HibernateException e) {
164 			if (tx != null)
165 				try {
166 					tx.rollback();
167 				} catch (HibernateException r) {
168 					this.logger.error(r);
169 					throw new ECARException("erro.hibernateException");
170 				}
171 			this.logger.error(e);
172 			throw new ECARException("erro.hibernateException");
173 		}
174 	}
175 
176 	/**
177 	 * Insere um objeto pai e uma coleção de objetos filhos utilizando uma
178 	 * transação do Hibernate.<br>
179 	 * 
180 	 * @author N/C
181 	 * @since N/C
182 	 * @version N/C
183 	 * @param Object
184 	 *            obj
185 	 * @param Collection
186 	 *            lista
187 	 * @throws ECARException
188 	 *             - executa o rollback da transação e dispara e exception
189 	 */
190 	@SuppressWarnings("unchecked")
191 	public void salvar(Object obj, Collection lista) throws ECARException {
192 		inicializarLogBean();
193 		Transaction tx = null;
194 		try {
195 			ArrayList objetosInseridos = new ArrayList();
196 			tx = session.beginTransaction();
197 
198 			// salva o pai
199 			session.save(obj);
200 			objetosInseridos.add(obj);
201 
202 			Iterator it = lista.iterator();
203 			while (it.hasNext()) {
204 				PaiFilho object = (PaiFilho) it.next();
205 				object.atribuirPKPai();
206 				// salva os filhos
207 				session.save(object);
208 				objetosInseridos.add(object);
209 			}
210 			tx.commit();
211 
212 			if (logBean != null) {
213 				logBean.setCodigoTransacao(Data.getHoraAtual(false));
214 				logBean.setOperacao("INC");
215 				Iterator it2 = objetosInseridos.iterator();
216 
217 				while (it2.hasNext()) {
218 					logBean.setObj(it2.next());
219 					loggerAuditoria.info(logBean.toString());
220 				}
221 			}
222 
223 		} catch (HibernateException e) {
224 			if (tx != null)
225 				try {
226 					tx.rollback();
227 				} catch (HibernateException r) {
228 					this.logger.error(r);
229 					throw new ECARException("erro.hibernateException");
230 				}
231 			this.logger.error(e);
232 			throw new ECARException("erro.hibernateException");
233 		}
234 	}
235 
236 	/**
237 	 * Salva um objeto utilizando uma transação do Hibernate.<br>
238 	 * 
239 	 * @author N/C
240 	 * @since N/C
241 	 * @version N/C
242 	 * @param Object
243 	 *            obj
244 	 * @throws ECARException
245 	 *             - executa o rollback da transação e dispara e exception
246 	 */
247 	public void salvarOuAlterar(Object obj) throws ECARException {
248 		inicializarLogBean();
249 		Transaction tx = null;
250 		try {
251 			tx = session.beginTransaction();
252 			session.saveOrUpdate(obj);
253 			tx.commit();
254 
255 			if (logBean != null) {
256 				logBean.setCodigoTransacao(Data.getHoraAtual(false));
257 				logBean.setObj(obj);
258 				logBean.setOperacao("INC_ALT");
259 				loggerAuditoria.info(logBean.toString());
260 			}
261 		} catch (HibernateException e) {
262 			if (tx != null)
263 				try {
264 					tx.rollback();
265 				} catch (HibernateException r) {
266 					this.logger.error(r);
267 					throw new ECARException("erro.hibernateException");
268 				}
269 			this.logger.error(e);
270 			throw new ECARException("erro.hibernateException");
271 		}
272 	}
273 
274 	/**
275 	 * Salva um objeto pai e uma coleção de objetos filhos utilizando uma
276 	 * transação do Hibernate.<br>
277 	 * 
278 	 * @author N/C
279 	 * @since N/C
280 	 * @version N/C
281 	 * @param Collection
282 	 *            lista
283 	 * @throws ECARException
284 	 *             - executa o rollback da transação e dispara e exception
285 	 */
286 	@SuppressWarnings("unchecked")
287 	public void salvarOuAlterar(Collection lista) throws ECARException {
288 		inicializarLogBean();
289 		Transaction tx = null;
290 		try {
291 
292 			tx = session.beginTransaction();
293 
294 			Iterator it = lista.iterator();
295 			while (it.hasNext()) {
296 				session.saveOrUpdate(it.next());
297 			}
298 			tx.commit();
299 
300 			if (logBean != null) {
301 				it = lista.iterator();
302 				logBean.setCodigoTransacao(Data.getHoraAtual(false));
303 				logBean.setOperacao("INC_ALT");
304 				while (it.hasNext()) {
305 					logBean.setObj(it.next());
306 					loggerAuditoria.info(logBean.toString());
307 				}
308 			}
309 
310 		} catch (HibernateException e) {
311 			if (tx != null)
312 				try {
313 					tx.rollback();
314 				} catch (HibernateException r) {
315 					this.logger.error(r);
316 					throw new ECARException("erro.hibernateException");
317 				}
318 			this.logger.error(e);
319 			throw new ECARException("erro.hibernateException");
320 		}
321 	}
322 
323 	/**
324 	 * Altera um objeto utilizando uma transação do Hibernate.<br>
325 	 * 
326 	 * @author N/C
327 	 * @since N/C
328 	 * @version N/C
329 	 * @param Object
330 	 *            obj
331 	 * @throws ECARException
332 	 *             - executa o rollback da transação
333 	 */
334 	public void alterar(Object obj) throws ECARException {
335 		inicializarLogBean();
336 		Transaction tx = null;
337 		try {
338 
339 			tx = session.beginTransaction();
340 			session.update(obj);
341 			tx.commit();
342 			if (logBean != null) {
343 				logBean.setCodigoTransacao(Data.getHoraAtual(false));
344 				logBean.setObj(obj);
345 				logBean.setOperacao("ALT");
346 				loggerAuditoria.info(logBean.toString());
347 			}
348 		} catch (HibernateException e) {
349 			if (tx != null)
350 				try {
351 					tx.rollback();
352 				} catch (HibernateException r) {
353 					this.logger.error(r);
354 					throw new ECARException("erro.hibernateException");
355 				}
356 			this.logger.error(e);
357 			throw new ECARException("erro.hibernateException");
358 		}
359 	}
360 
361 	/**
362 	 * Altera um objeto pai e salva uma coleção de Filhos utilizando uma
363 	 * transação do Hibernate.<br>
364 	 * 
365 	 * @author N/C
366 	 * @since N/C
367 	 * @version N/C
368 	 * @param Object
369 	 *            obj
370 	 * @param Collection
371 	 *            lista
372 	 * @throws ECARException
373 	 *             - executa o rollback da transação
374 	 */
375 	@SuppressWarnings("unchecked")
376 	public void alterar(Object obj, Collection lista) throws ECARException {
377 		inicializarLogBean();
378 		Transaction tx = null;
379 		try {
380 			ArrayList objetosAlterados = new ArrayList();
381 
382 			tx = session.beginTransaction();
383 			session.update(obj);
384 			objetosAlterados.add(obj);
385 
386 			Iterator it = lista.iterator();
387 			while (it.hasNext()) {
388 				PaiFilho object = (PaiFilho) it.next();
389 				object.atribuirPKPai();
390 				// salva os filhos
391 				session.save(object);
392 				objetosAlterados.add(object);
393 			}
394 			tx.commit();
395 
396 			if (logBean != null) {
397 				logBean.setCodigoTransacao(Data.getHoraAtual(false));
398 				logBean.setOperacao("ALT");
399 				Iterator it2 = objetosAlterados.iterator();
400 
401 				while (it2.hasNext()) {
402 					logBean.setObj(it2.next());
403 					loggerAuditoria.info(logBean.toString());
404 				}
405 			}
406 		} catch (HibernateException e) {
407 			if (tx != null)
408 				try {
409 					tx.rollback();
410 				} catch (HibernateException r) {
411 					this.logger.error(r);
412 					throw new ECARException("erro.hibernateException");
413 				}
414 			this.logger.error(e);
415 			throw new ECARException("erro.hibernateException");
416 		}
417 	}
418 
419 	/**
420 	 * Altera uma coleção de objetos utilizando uma transação do Hibernate.<br>
421 	 * 
422 	 * @author N/C
423 	 * @since N/C
424 	 * @version N/C
425 	 * @param Collection
426 	 *            lista
427 	 * @throws ECARException
428 	 *             - executa o rollback da transação e dispara e exception
429 	 */
430 	@SuppressWarnings("unchecked")
431 	public void alterar(Collection lista) throws ECARException {
432 		inicializarLogBean();
433 		Transaction tx = null;
434 		try {
435 
436 			tx = session.beginTransaction();
437 
438 			Iterator it = lista.iterator();
439 			while (it.hasNext()) {
440 				session.update(it.next());
441 			}
442 			tx.commit();
443 
444 			if (logBean != null) {
445 				it = lista.iterator();
446 				logBean.setCodigoTransacao(Data.getHoraAtual(false));
447 				logBean.setOperacao("ALT");
448 				while (it.hasNext()) {
449 					logBean.setObj(it.next());
450 					loggerAuditoria.info(logBean.toString());
451 				}
452 			}
453 		} catch (HibernateException e) {
454 			if (tx != null)
455 				try {
456 					tx.rollback();
457 				} catch (HibernateException r) {
458 					this.logger.error(r);
459 					throw new ECARException("erro.hibernateException");
460 				}
461 			this.logger.error(e);
462 			throw new ECARException("erro.hibernateException");
463 		}
464 	}
465 
466 	/**
467 	 * Exclui um objeto passando a classe e a chave como parâmetro.<br>
468 	 * Primeiro carrega o objeto na sessão e depois cria uma transação para
469 	 * excluir.<br>
470 	 * 
471 	 * @author N/C
472 	 * @since N/C
473 	 * @version N/C
474 	 * @param Object
475 	 *            obj
476 	 * @throws ECARException
477 	 *             - executa o rollback da transação
478 	 */
479 	public void excluir(Object obj) throws ECARException {
480 		inicializarLogBean();
481 		Transaction tx = null;
482 		try {
483 			tx = session.beginTransaction();
484 			session.delete(obj);
485 			tx.commit();
486 			if (logBean != null) {
487 				logBean.setCodigoTransacao(Data.getHoraAtual(false));
488 				logBean.setObj(obj);
489 				logBean.setOperacao("EXC");
490 				loggerAuditoria.info(logBean.toString());
491 			}
492 		} catch (HibernateException e) {
493 			if (tx != null)
494 				try {
495 					tx.rollback();
496 				} catch (HibernateException r) {
497 					this.logger.error(r);
498 					throw new ECARException("erro.hibernateException");
499 				}
500 			this.logger.error(e);
501 			throw new ECARException("erro.hibernateException");
502 		}
503 	}
504 
505 	/**
506 	 * Exclui uma lista de objetos. A lista deve estar na ordem tal que não gere
507 	 * violação de integridade.<br>
508 	 * 
509 	 * @author N/C
510 	 * @since N/C
511 	 * @version N/C
512 	 * @param Collection
513 	 *            lista
514 	 * @throws ECARException
515 	 *             - executa o rollback da transação
516 	 */
517 	@SuppressWarnings("unchecked")
518 	public void excluir(Collection lista) throws ECARException {
519 		inicializarLogBean();
520 		Transaction tx = null;
521 		try {
522 			tx = session.beginTransaction();
523 			Iterator it = lista.iterator();
524 			while (it.hasNext())
525 				session.delete(it.next());
526 			tx.commit();
527 
528 			if (logBean != null) {
529 				it = lista.iterator();
530 				logBean.setCodigoTransacao(Data.getHoraAtual(false));
531 				logBean.setOperacao("EXC");
532 				while (it.hasNext()) {
533 					logBean.setObj(it.next());
534 					loggerAuditoria.info(logBean.toString());
535 				}
536 			}
537 		} catch (HibernateException e) {
538 			if (tx != null)
539 				try {
540 					tx.rollback();
541 				} catch (HibernateException r) {
542 					this.logger.error(r);
543 					throw new ECARException("erro.hibernateException");
544 				}
545 			this.logger.error(e);
546 			throw new ECARException("erro.hibernateException");
547 		}
548 	}
549 
550 	/**
551 	 * Busca um objeto do banco de dados pela chave.<br>
552 	 * 
553 	 * @author N/C
554 	 * @since N/C
555 	 * @version N/C
556 	 * @param Class
557 	 *            cl - classe do objeto a buscar
558 	 * @param Serializable
559 	 *            chave - PK
560 	 * @return Object - um objeto reencarnado do banco de dados da classe
561 	 *         informada
562 	 * @throws ECARException
563 	 *             - NAO tem rollback
564 	 */
565 	@SuppressWarnings("unchecked")
566 	public Object buscar(Class cl, Serializable chave) throws ECARException {
567 		Object obj = null;
568 		try {
569 			/*
570 			 * atenção. o session.load joga o objeto para o cache interno do
571 			 * hibernate
572 			 */
573 			/* TODO descobrir a melhor maneira de lidar com o cache do hibernate */
574 			/*
575 			 * isto é, quando deve ser aproveitado o cache e quando ele deve ser
576 			 * limpo
577 			 */
578 			/*
579 			 * para evitar que ocorra uma carga desatualizada de um objeto do
580 			 * cache
581 			 */
582 			/*
583 			 * descobrir que metodos do hibernate lêem o cache e quais gravam no
584 			 * cache
585 			 */
586 
587 			obj = session.load(cl, chave);
588 		} catch (ObjectNotFoundException e) {
589 			// this.logger.error(e);
590 			throw new ECARException("erro.objectNotFound");
591 		} catch (HibernateException e) {
592 			this.logger.error(e);
593 			throw new ECARException("erro.hibernateException");
594 		} catch (Exception e) {
595 			this.logger.error(e);
596 			throw new ECARException("erro.exception");
597 		}
598 		return (obj);
599 	}
600 
601 	/**
602 	 * Método para pesquisar objetos.<br>
603 	 * Recebe um objeto a pesquisar e um array de ordenações e devolve uma lista
604 	 * de objetos do tipo informado.<br>
605 	 * Os atributos a pesquisar devem estar setados no objeto antes da chamada.<br>
606 	 * Exemplo:<br>
607 	 * Pessoa p = new Pessoa();<br>
608 	 * p.setNome("Joao%"); // argumento de pesquisa. o metodo vai pesquisar por
609 	 * nome.<br>
610 	 * List l1 = PessoaDao.pesquisar(p, new String[]{"nome","asc"}); // ordena
611 	 * por nome ascendente.<br>
612 	 * sempre passar o array de ordenacao aos pares campo e ordem.<br>
613 	 * List l2 = PessoaDao.pesquisar(p, null); // nenhuma ordenacao ou ordem
614 	 * natural.<br>
615 	 * <p>
616 	 * Esse método deve ser utilizado preferencialmente para as classes POJO que
617 	 * contenham<br>
618 	 * métodos get e seus respectivos atributos, porque utiliza essa estrutura
619 	 * para descobrir<br>
620 	 * os atributos que estão preenchidos com os argumentos da pesquisa.<br>
621 	 * <p>
622 	 * Utiliza a expressao like para realizar a pesquisa em cada um dos
623 	 * atributos preenchidos.<br>
624 	 * Para funcionar corretamente os atributos que nao devem entrar na pesquisa
625 	 * precisam conter null.<br>
626 	 * 
627 	 * @author N/C
628 	 * @since N/C
629 	 * @version N/C
630 	 * @param Object
631 	 *            obj - o objeto de pesquisa
632 	 * @param String
633 	 *            [] ordem - array de pares de string contendo os campos para
634 	 *            ordenacao
635 	 * @return List - lista de objetos do tipo pesquisado
636 	 * @throws ECARException
637 	 */
638 	@SuppressWarnings("unchecked")
639 	public List pesquisar(Object obj, String[] ordem) throws ECARException {
640 
641 		List list = new ArrayList(); // lista resultado
642 		Criteria select; // select (do hibernate)
643 
644 		if (obj == null)
645 			return list;
646 
647 		try {
648 			/*
649 			 * limpa os objeto do cache antes de buscar, para garantir que a
650 			 * busca será no BD e nao no cache
651 			 */
652 			/* TODO avaliar e utilizacao do cache */
653 			// clearSession();
654 			select = session.createCriteria(obj.getClass());
655 			List listaMetodos = Util.listaMetodosGet(obj);
656 			Object auxObj;
657 			String nomeAtributo;
658 			String nomeMetodo;
659 			String tipoRetorno;
660 			for (int i = 0; i < listaMetodos.size(); i++) {
661 				auxObj = ((Method) listaMetodos.get(i)).invoke(obj,
662 						new Object[] {});
663 				// somente adiciona um criterio se o conteudo for != vazio
664 				if (auxObj != null) {
665 					// obtem o nome do método para retirar o nome do atributo
666 					nomeMetodo = ((Method) listaMetodos.get(i)).getName();
667 					tipoRetorno = ((Method) listaMetodos.get(i))
668 							.getReturnType().getName().toLowerCase();
669 					nomeAtributo = nomeMetodo.substring(3, 4).toLowerCase()
670 							+ nomeMetodo.substring(4);
671 
672 					if (tipoRetorno.endsWith("string"))
673 						select.add(Expression.ilike(nomeAtributo, "%" + auxObj
674 								+ "%"));
675 					else {
676 						// Se o atributo for Set não entra na pesquisa será
677 						// filtrado depois
678 						if (!tipoRetorno.endsWith("set"))
679 							select.add(Expression.eq(nomeAtributo, auxObj));
680 					}
681 				}
682 			}
683 
684 			if (ordem != null)
685 				for (int i = 0; i < ordem.length; i += 2)
686 					// anda aos pares
687 					if (ordem[i + 1].equalsIgnoreCase(Dao.ORDEM_ASC))
688 						select.addOrder(Order.asc(ordem[i]));
689 					else if (ordem[i + 1].equalsIgnoreCase(Dao.ORDEM_DESC))
690 						select.addOrder(Order.desc(ordem[i]));
691 
692 			list = select.list();
693 
694 		} catch (HibernateException e) {
695 			this.logger.error(e);
696 			throw new ECARException("erro.hibernateException");
697 		} catch (IllegalAccessException e) {
698 			this.logger.error(e);
699 			throw new ECARException("erro.exception");
700 		} catch (IllegalArgumentException e) {
701 			this.logger.error(e);
702 			throw new ECARException("erro.exception");
703 		} catch (InvocationTargetException e) {
704 			this.logger.error(e);
705 			throw new ECARException("erro.exception");
706 		}
707 
708 		return list;
709 	}
710 
711 	/**
712 	 * Devolve uma lista de objetos com campos duplicados.<br>
713 	 * Pesquisa, a partir do objeto passado como parâmetro, os campos que não
714 	 * podem conter valores duplicados.<br>
715 	 * Por exemplo, num cadastro de pessoas, não pode haver duas pessoas com o
716 	 * mesmo CNPJ ou o mesmo Nome.<br>
717 	 * 
718 	 * @author N/C
719 	 * @since N/C
720 	 * @version N/C
721 	 * @param Object
722 	 *            obj - objeto que se deseja inserir ou alterar no banco de
723 	 *            dados
724 	 * @param String
725 	 *            [] nomeCamposNaoDuplos - array com o nome dos campos que não
726 	 *            podem conter duplicatas.
727 	 * @param String
728 	 *            nomeChave - nome do campo chave (codigo) para que nao retorne
729 	 *            o proprio registro.
730 	 * @return List - uma lista de objetos que contém campos duplicados ou uma
731 	 *         lista vazia cc.
732 	 * @throws ECARException
733 	 */
734 	@SuppressWarnings("unchecked")
735 	public List pesquisarDuplos(Object obj, String[] nomeCamposNaoDuplos,
736 			String nomeChave) throws ECARException {
737 
738 		List list = new ArrayList();
739 		Criteria select;
740 
741 		if (obj == null)
742 			return list;
743 
744 		try {
745 			/*
746 			 * não dá para usar clearSession aqui, porque esse método será
747 			 * utilizando momentos antes de salvar ou atualizar um objeto. Ao
748 			 * salvar ou atualizar um objeto, são utilizados alguns dados que
749 			 * estão no cache, por exemplo collection do objeto que será
750 			 * trabalhado. clearSession();
751 			 */
752 
753 			select = session.createCriteria(obj.getClass());
754 			Object auxObj;
755 			String nomeAtributo;
756 			String tipoRetorno;
757 			Criterion crit = Expression.sql("1 = 0"); // Adiciona um expressão
758 			// falsa para não
759 			// interferir nas
760 			// clausulas where
761 			for (int i = 0; i < nomeCamposNaoDuplos.length; i++) {
762 				nomeAtributo = nomeCamposNaoDuplos[i];
763 				auxObj = Util.invocaGet(obj, nomeAtributo);
764 				tipoRetorno = auxObj.getClass().getName().toLowerCase();
765 				// somente adiciona um criterio se o conteudo for != vazio
766 				if (auxObj != null) {
767 					if (tipoRetorno.endsWith("string"))
768 						crit = Expression.or(crit, Expression.ilike(
769 								nomeAtributo, auxObj));
770 					else {
771 						// Se o atributo for Set não entra na pesquisa será
772 						// filtrado depois
773 						if (!tipoRetorno.endsWith("set"))
774 							crit = Expression.or(crit, Expression.eq(
775 									nomeAtributo, auxObj));
776 					}
777 				}
778 			}
779 			select.add(crit);
780 
781 			// adiciona o nome do campo codigo que deve ser diferente do atual
782 			auxObj = Util.invocaGet(obj, nomeChave);
783 			if (auxObj != null)
784 				select.add(Expression.not(Expression.eq(nomeChave, auxObj)));
785 			list = select.list();
786 
787 		} catch (HibernateException e) {
788 			this.logger.error(e);
789 			throw new ECARException("erro.hibernateException");
790 		} catch (IllegalArgumentException e) {
791 			this.logger.error(e);
792 			throw new ECARException("erro.exception");
793 		}
794 		return list;
795 	}
796 
797 	/**
798 	 * Devolve uma lista de objetos de uma determinada classe.<br>
799 	 * 
800 	 * @author N/C
801 	 * @since N/C
802 	 * @param Class
803 	 *            cl - classe do objeto
804 	 * @param String
805 	 *            [] ordem - array com a sequencia de ordenacao a ser utilizada
806 	 *            (aos pares)
807 	 * @return List - lista de objetos de acordo com os parametros especificados<br>
808 	 *         Exemplo de utilizacao<br>
809 	 *         List l = corDao.listar(Cor.class, new String[]
810 	 *         {"nomeCor",Dao.ORDEM_ASC});<br>
811 	 *         List l = corDao.listar(Cor.class, new String[]
812 	 *         {"significadoCor","asc"});<br>
813 	 * @throws ECARException
814 	 */
815 	@SuppressWarnings("unchecked")
816 	public List listar(Class cl, String[] ordem) throws ECARException {
817 		List list = null;
818 
819 		if (cl == null)
820 			return list;
821 
822 		try {
823 			/*
824 			 * não dá para usar clearSession aqui, porque limpará a session e
825 			 * assim outros objetos que já tenham sido carregados e estejam
826 			 * sendo usados na construção da página serão perdidos
827 			 * clearSession();
828 			 */
829 
830 			Criteria c = session.createCriteria(cl);
831 
832 			if (ordem != null)
833 				for (int i = 0; i < ordem.length; i += 2)
834 					// anda aos pares
835 					if (ordem[i + 1].equalsIgnoreCase(Dao.ORDEM_ASC))
836 						c.addOrder(Order.asc(ordem[i]));
837 					else if (ordem[i + 1].equalsIgnoreCase(Dao.ORDEM_DESC))
838 						c.addOrder(Order.desc(ordem[i]));
839 
840 			list = c.list();
841 
842 		} catch (HibernateException e) {
843 			this.logger.error(e);
844 			throw new ECARException("erro.hibernateException");
845 		}
846 		return list;
847 	}
848 
849 	/**
850 	 * Ordena.<br>
851 	 * 
852 	 * @author N/C
853 	 * @since N/C
854 	 * @version N/C
855 	 * @param Set
856 	 *            colecao
857 	 * @param String
858 	 *            campo
859 	 * @param String
860 	 *            ordem
861 	 * @return List
862 	 * @throws ECARException
863 	 */
864 	@SuppressWarnings("unchecked")
865 	public List ordenaSet(Set colecao, String campo, String ordem)
866 			throws ECARException {
867 		try {
868 			return this.getSession().createFilter(colecao,
869 					" order by " + campo + " " + ordem).list();
870 		} catch (HibernateException e) {
871 			this.logger.error(e);
872 			throw new ECARException("erro.hibernateException");
873 		}
874 
875 	}
876 
877 	/**
878 	 * Inicializa o objeto de Log.
879 	 * 
880 	 * @author N/C
881 	 * @since N/C
882 	 * @version N/C
883 	 */
884 	public void inicializarLogBean() {
885 		this.logBean = null;
886 		if (this.request != null) {
887 			this.loggerAuditoria = Logger.getLogger("AUDITORIA");
888 			SegurancaECAR seguranca = (SegurancaECAR) this.request.getSession()
889 					.getAttribute("seguranca");
890 			this.logBean = new LogBean();
891 			this.logBean.setIPUsuario(this.request.getRemoteAddr());
892 			this.logBean.setUsuario(seguranca.getUsuario());
893 			this.logBean.setCodigoSessao(this.request.getSession().getId());
894 		}
895 	}
896 }