org.hibernate.impl.SessionImpl cannot be cast to org.hibernate.engine.spi.SessionImplementor While using Full Text Search - hibernate-search

I am using hibernate-search-4.5.2.Final to implement a full text search but getting an exception with following message
org.hibernate.impl.SessionImpl cannot be cast to org.hibernate.engine.spi.SessionImplementor
in the following line
FullTextSession fullTextSession = Search.getFullTextSession(sessionImpl.getFactory().openSession());
This is my code:
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("rawtypes")
#Override
public List getFuzzySearchedResult(String query_string) {
try {
Session session = sessionFactory.openSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
final QueryBuilder mythQB = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(FaqMaster.class).get();
org.apache.lucene.search.Query luceneQuery = mythQB.phrase().withSlop(3).onField("question_name").andField("qustion_answer").sentence("Department").createQuery();
org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery);
List result = fullTextQuery.list();
return result;
}
catch(Exception e){System.out.println("ERROR: "); e.printStackTrace(); return null;}
}
Please help.

You are using a version of Hibernate ORM which is not compatible with this version of Hibernate Search.
All versions of Hibernate Search 4.5.x require a version of Hibernate ORM in the series 4.3.x.
This is documented:
On the Downloads page
In the Requirements section of the documentation
In the README of the project
In the Maven pom files
But you're not the first person getting confused by this ;-) So I'm wondering now if we should add an explicit check and more understandable error message. I've created HSEARCH-1816 to see if we can do better.

Related

How to implement near-real time autocompletion using lucene?

Lucene offers different Autocompletion options:
org.apache.lucene.search.suggest.Lookup
I was using the AnalyzingSuggester which is good but it does not support changing data, i.e. when the index changes one needs to reindex everything.
Therefore I tries out the AnalyzingInfixSuggester. This has and add method and an update method but no remove.
Does someone know if it is possible to implement near-real time suggestions with pure lucene?
I do not know why this is not part of the public implementation. At the end I extended the AnalyzingInfixSuggester like this:
public class MyAnalyzingInfixSuggester extends AnalyzingInfixSuggester {
public MyAnalyzingInfixSuggester(Directory dir, Analyzer analyzer) throws IOException {
super(dir, analyzer);
}
public void remove(String text) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
// call method ensureOpen via reflection since it is private
Method method = AnalyzingInfixSuggester.class.getDeclaredMethod("ensureOpen");
method.setAccessible(true);
method.invoke(this);
Query query1 = new TermQuery(new Term(TEXT_FIELD_NAME, text.toLowerCase()));
BooleanQuery booleanQuery = new BooleanQuery.Builder()
.add(query1, BooleanClause.Occur.MUST)
.build();
writer.deleteDocuments(booleanQuery);
}
}

EclipseLink JPA Dynamic model and Criteria Query

i like to create a (crtieria-) query against a dynamic model but i always get the exception
No [EntityType] was found for the key class [demo.DynamicResult] in the Metamodel
at the last line
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Tuple> query = criteriaBuilder.createTupleQuery();
DynamicHelper helper = new DynamicHelper(JpaHelper.getServerSession(emf));
Class<? extends DynamicEntity> rootclass = helper.getType("demo.DynamicResult").getJavaClass();
query.from(rootclass);
The DynamicResult gets generated with following code
ServerSession serverSession = JpaHelper.getEntityManager(entityManager).getServerSession();
DynamicClassLoader dcl = DynamicClassLoader.lookup(serverSession);
JPADynamicHelper jpaDynamicHelper = new JPADynamicHelper(entityManager);
Class<?> dynamicResult = dcl.createDynamicClass("demo.DynamicResult");
JPADynamicTypeBuilder dynamicResultBuilder = new JPADynamicTypeBuilder(dynamicResult, null, "DynamicResult");
dynamicResultBuilder.addDirectMapping("id", String.class, "id");
//Some more addDirectMappings ....
dynamicResultBuilder.setPrimaryKeyFields("id");
type = dynamicResultBuilder.getType();
jpaDynamicHelper.addTypes(false, false, type);
What did I missed ?
Is this kind of query possible at all ?
Regards
You may be hitting https://bugs.eclipse.org/bugs/show_bug.cgi?id=429760 bug. There was a problem with copying newly created dynamic entity metadata into current session.
Check this bug and attached diffs. jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/tests/jpa/dynamic/simple/SimpleQueryTestSuite.java test suite contains test which does similar thing - creates dynamic entity and runs JPQL query against it within the same transaction (UnitOfWork).
I would try latest 2.7.0 or 2.6.1 (do not use .WAS) build from https://www.eclipse.org/eclipselink/downloads/nightly.php to see if it works fine for you.

JPA - Is there a way/method to retrieve Persistence Unit information

I'd like to find out my data source name in the code. Is there a way of doing that?
I am using eclipselink.
thanks
To be more specific, my aim is to get an jdbc connection object.
I know i can do that thru:
datasource = (DataSource) (new InitialContext()).lookup("my_data_source_name")
connection = dataSource.getConnection();
But I don't want to hard code the data source name in my code.
I also tried
java.sql.Connection connection = em.unwrap(java.sql.Connection.class);
and it always return null.
.unwrap() should be the way to go, as written in EclipseLink wiki.
I also used to get null when calling em.unwrap(java.sql.Connection.class); because it was not inside a transaction. When called like this:
em.getTransaction().begin();
java.sql.Connection conn = em.unwrap(java.sql.Connection.class);
// ...
em.getTransaction().commit();
everything works fine!
java.sql.Connection connection = em.unwrap(java.sql.Connection.class);
Should work, what version are you using? Ensure that a transaction is active.
To get the data source name you should be able to use,
((JNDIConnector)em.unwrap(JpaEntityManager.class).getSession().getLogin().getConnector()).getName();
Here's what I've found helpful:
private DataSource createDataSource() {
ClientDataSource dataSource = new ClientDataSource();
dataSource.setServerName("localhost");
dataSource.setPortNumber(1527);
dataSource.setDatabaseName("sample");
dataSource.setUser("app");
dataSource.setPassword("app");
return dataSource;
}
private EntityManagerFactory getEntityManagerFactory() {
if (emf == null) {
Map properties = new HashMap();
properties
.put(PersistenceUnitProperties.NON_JTA_DATASOURCE,createDataSource());
emf = Persistence.createEntityManagerFactory(PU_NAME, properties);
}
return emf;
}
Can you create your datasource in the code, rather than configure via persistence.xml?

How to implement "delete all" for a Spring Roo Entity?

I'm trying to delete all database entries for a Spring Roo entity. When I look at *_Roo_Entity.aj it seems as if there is no "delete all" method. I tried to implement it myself (Licences is the name of the Roo entity. Don't mind the naming. It was reverese engineered from a database and may be changed later):
public static int Licences.deleteAll() {
return entityManager().createQuery("delete from Licences o").executeUpdate();
}
It compiles just fine but when I call Licences.deleteAll() I get the following exception:
org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query;
nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query (NativeException)
Adding #Transactional doesn't make a difference.
What am I missing here?
Is this approach completely wrong and I need to implement it like this:
public static void Licences.deleteAll() {
for (Licences licence : findAllLicenceses()) {
licence.remove();
}
}
This works, but is JPA smart enough to translate this into a delete from licences query or will it create n queries?
#Transactional doesn't work on static function
change
public static int Licences.deleteAll() {
return entityManager().createQuery("delete from Licences o").executeUpdate();
}
to
public int Licences.deleteAll() {
return entityManager().createQuery("delete from Licences o").executeUpdate();
}
https://jira.springsource.org/browse/SPR-5999
Bye
JPA does not have a delete all functionality. (even not with JQL!)
At least there are only three ways:
The loop, like you did
A JPQL Query see: JPQL Reference: 10.2.9. JPQL Bulk Update and Delete
A native SQL Query, but this will cause many problems with Entity Manager caches!
BTW: It seams that you are using AspectJ to attach you delete method. - You can do this (even if I do not know, why not adding the static method direct to the Entity class), but you must not touch the Roo generated aj files!
public static int Licences.deleteAll() {
return new Licences().deleteAllTransactional();
}
#Transactional
private int Licences.deleteAllTransactional() {
if (this.entityManager == null) this.entityManager = entityManager();
return this.entityManager.createQuery("delete from Licences o").executeUpdate();
}

gwt-rpc + appengine + persistence using restlet throws exception

I was trying to rebuild the Restlet sample Application for GWT + GAE ( http://wiki.restlet.org/docs_2.1/13-restlet/21-restlet/318-restlet/303-restlet.html ) .
I changed it a bit, since I am planning something diffrent but I thought it would be a good start.
It was going okish until now. The "Put" was coming through to app engine but when i tried to persist the Objects using JPA i get the following Exception:
Caused by: org.datanucleus.exceptions.ClassNotResolvedException: Class "de.fr1zle.shoplist.web.gae.client.ShoppingListRessourceProxy" was not found in the CLASSPATH. Please check your specification and your CLASSPATH.
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:250)
at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:415)
at org.datanucleus.metadata.MetaDataManager.loadPersistenceUnit(MetaDataManager.java:767)
... 79 more
As you can see, datanucleus somehow tries to access the GWT Proxy class when loading the info from the persistence.xml.
I use the following in my ServerRessource:
#Put
public void putShoppingList(ShoppingList shoppingList) {
ShoppingListDOA shoppingListDOA = new ShoppingListDOA(shoppingList);
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("transactions-optional");
try {
EntityManager entityManager = emf.createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(shoppingListDOA);
entityManager.flush();
transaction.commit();
entityManager.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (emf != null)
emf.close();
}
}
I somehow have the feeling that DataNucleus enhances the Proxy Class, too although I changed the properites for it to not do so.
Using: GAE 1.4.2 (tried 1.4.3, too) , GWT 2.2 and Restlet 2.1m3
Am I missing a point here? Your help is appricated :-)
Thanks in advance!
fr1zle