I followed the annotations approach and it didn't work for me even though I'm using JDK 5.0. Can I use annotations without using EJB?
I have temporarily solved the problem with a different approach:
Here is the code (not yet finished or properly tested) (The Searchable interface interface is the same as in the integration example):
Code:
<hibernate-configuration>
<session-factory>
...
<!-- lucene indexer -->
<listener type="post-update" class="com.estudiowebs.CMS.DAO.LuceneHibernateEventListener" />
<listener type="post-insert" class="com.estudiowebs.CMS.DAO.LuceneHibernateEventListener" />
<listener type="post-delete" class="com.estudiowebs.CMS.DAO.LuceneHibernateEventListener" />
</session-factory>
</hibernate-configuration>
Code:
public class LuceneHibernateEventListener implements PostInsertEventListener,
PostUpdateEventListener, PostDeleteEventListener {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Drop object from Lucene index
*/
public void drop(Searchable entity, Long id) throws IOException {
System.out.println("Drop in index called for:" + entity);
IndexReader reader = entity.getIndexReader();
reader.delete(new Term("id", String.valueOf(id)));
}
/**
* Add object to Lucene index
*/
public void add(Searchable entity, Long id) throws IOException {
System.out.println("Add to index called for:" + entity);
Document doc = entity.getDocument();
doc.add(Field.Keyword("id", String.valueOf(id)));
doc.add(Field.Keyword("classname", entity.getClass().getName()));
IndexWriter writer = entity.getIndexWriter();
writer.addDocument(doc);
writer.close();
}
public void onPostInsert(PostInsertEvent event) {
System.out.println("LuceneInterceptor onSave called for: "
+ event.getEntity() + " id " + event.getId());
if (event.getEntity() instanceof Searchable) {
try {
add((Searchable) event.getEntity(),
resolveToLong(event.getId()));
} catch (IOException e) {
throw new CallbackException(e.getMessage());
}
}
}
public void onPostUpdate(PostUpdateEvent event) {
System.out.println("onFlushDirty called for:" + event.getEntity()
+ " id " + event.getId());
if (event.getEntity() instanceof Searchable) {
try {
drop((Searchable) event.getEntity(), resolveToLong(event
.getId()));
add((Searchable) event.getEntity(),
resolveToLong(event.getId()));
} catch (IOException e) {
throw new CallbackException(e.getMessage());
}
}
}
public void onPostDelete(PostDeleteEvent event) {
if (event.getEntity() instanceof Searchable) {
try {
drop((Searchable) event.getEntity(), resolveToLong(event
.getId()));
} catch (IOException e) {
throw new CallbackException(e.getMessage());
}
}
}
private Long resolveToLong(Serializable id) {
if (id instanceof Integer) {
return new Long((Integer) id);
} else if (id instanceof String) {
return Long.valueOf((String) id);
} else if (id instanceof Long) {
return (Long) id;
}
return null;
}
}