Hibernate Search e Tomcat

Olá Pessoal,

Estou tentando usar o Hibernate Search com Lucene no meu projeto e estou encontrando problema.

Quando rodo um teste em JUnit funciona tudo certo, mas quando testo dentro do meu sistema obtenho a seguinte exceção
org.hibernate.HibernateException: Hibernate Search Event listeners not configured, please check the reference documentation and the application’s hibernate.cfg.xml

Estou usando JSF e Hibernate com JPA, não estou usando hibernate.cfg.xml, mas sim o persistence.xml, o qual não fiz nenhuma configuração. No mais, segue abaixo o meu código do JUnit.

	private static void initInidexLucene(){
		FullTextSession fullTextSession = Search.createFullTextSession((Session)em.getDelegate());
		//fullTextSession.setFlushMode(FlushMode.MANUAL);
		fullTextSession.setFlushMode(FlushMode.AUTO);
		fullTextSession.setCacheMode(CacheMode.IGNORE);
		Transaction transaction = fullTextSession.beginTransaction();
		//Scrollable results will avoid loading too many objects in memory
		ScrollableResults results = fullTextSession.createCriteria( Acordao.class ).scroll( ScrollMode.FORWARD_ONLY );
		//int index = 0;
		//int batchSize = 5000;
		while( results.next() ) {
		  //  index++;
		    fullTextSession.index( results.get(0) ); //index each element
		    //if (index % batchSize == 0) 
		    	//fullTextSession.clear(); //clear every batchSize since the queue is processed
		}
		transaction.commit();			
	}
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		Logger.getLogger("org").setLevel(Level.ERROR);
		Map<String, String> configOverrides = new HashMap<String, String>();
		configOverrides.put("hibernate.connection.username", "root");
		configOverrides.put("hibernate.connection.password", "1324");
		emf = Persistence.createEntityManagerFactory(
				"persistenceUnit", configOverrides);
		em = emf.createEntityManager();
		initInidexLucene();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		if (em != null) {
			em.close();
			em = null;
		}
		if (emf != null) {
			emf.close();
			emf = null;
		}		
	}
	@Test
	public void testLucene() {
		try {
			FullTextSession fullTextSession = Search.createFullTextSession((Session)em.getDelegate());
			
			String[] stopWords = new String[]{"de","do","da","dos","das","a","o","na","no","em"};     
            System.out.println("suche gestartet!");
            
         // also tried it with contact.street as field name
            QueryParser parser = new QueryParser("ementa", new StopAnalyzer(stopWords)); 
            
            org.apache.lucene.search.Query luceneQuery;
            luceneQuery = parser.parse("instrumento"); // want to see all streets starting with the letter 'w'
            org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery);
            System.out.println("fulltextquery: " + fullTextQuery.toString());
            List result = fullTextQuery.list();
            System.out.println("result.size(): " + result.size());
         } catch (Exception e) {
            e.printStackTrace();
         } 		
	}
 

Utilizando o hibernate.cfg.xml é necessário adicionar estas tags ao nodo

	<event type="post-update">
		<listener
			class="org.hibernate.search.event.FullTextIndexEventListener" />
	</event>
	<event type="post-insert">
		<listener
			class="org.hibernate.search.event.FullTextIndexEventListener" />
	</event>
	<event type="post-delete">
		<listener
			class="org.hibernate.search.event.FullTextIndexEventListener" />
	</event>

Agora você precisa achar o equivalente em JPA.

Quando uso JPA, a configuração não deveria ser dentro do persistence.xml? Posso usar o hibernate.cfg.xml e o persistence.xml ao mesmo tempo sem apresentar conflito?

Ademais, o sistema está funcionando corretamente quando executado no JUnit. A exceção somente é apresentada quando faço o deploy para o Tomcat.

Olá LIPE,

Finalmente consegui resolver o problema. Primeiramente, criei o hibernate.cfg.xml com os dados que você sugeriu e adicionei a propriedade

<property name="hibernate.ejb.cfgfile"
				value="META-INF/hibernate.cfg.xml" />

dentro do persistence.xml, na medida em que uso JPA e precisava integrá-lo com o hibernate.cfg.xml. Contudo me deparei com uma outra mensagem de erro:

java.lang.VerifyError: (class: org/hibernate/search/event/FullTextIndexEventListener, method: onPostInsert signature: (Lorg/hibernate/event/PostInsertEvent;)V) Incompatible argument to function
O motivo desse último erro era um bug existente na versão do hibernate que eu trabalhava (vide http://www.guj.com.br/posts/list/69209.java ). Solucionei o problema baixando todas as versões mais recentes do hibernate-core, hibernate-annotation e hibernate-entitymanager. Feito isso, tudo funcionou corretamente. Não precisei nem das propriedades do hibernate.cfg.xml.

up

Estou com um problema relacionado a este assunto,

Estou pesquisando em todos os lugares possíveis, já acionei 4 amigos especialistas em java, certificados e tudo mais.
Lancei perguntas em forum, baixei o manual do Hibernate Search, estou pirando aqui e ninguém tem idéia de como resolver.
Só preciso fazer o reload do arquivo de sinônimos (synonimus.txt) depois dele ser alterado (em ambiente de produção, sem precisar reiniciar o servidor).

Alguém tem alguma referência, alguem que eu possa ligar, uma idéia de como fazer isso?