JPA HibernateSearch Projections - java

I'm trying to use JPA with HibernateSearch. I used Example 5.3 in http://docs.jboss.org/hibernate/stable/search/reference/en/html/search-query.html. The results come out as expected.
However, the data coming back is a huge graph. I only need the primary key of the data. So, I tried Example 5.9, but it only shows the Hibernate API. There was not a javax.persistence.Query.setProjection() method.
What can I use to get just the primary key of a search result? Should I try to get the hibernate session from the EntityManager in JPA?
Thanks for any help.

Example 5.3 was a bit misleading. javax.persistence.Query doesn't have to be used. Instead, org.hibernate.search.jpa.FullTextQuery has the setProjection() method that I needed. Here is the resulting code (with fully qualified class names):
//Open JPA session
javax.persistence.EntityManagerFactory emf=javax.persistence.Persistence.createEntityManagerFactory("manager1");
javax.persistence.EntityManager em=emf.createEntityManager();
em.getTransaction().begin();
//Make a FullText EM from the JPA session.
org.hibernate.search.jpa.FullTextEntityManager fullTextSession=org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
//Build the lucene query.
org.apache.lucene.queryParser.QueryParser parser=new org.apache.lucene.queryParser.QueryParser("data1",new org.apache.lucene.analysis.standard.StandardAnalyzer());
org.apache.lucene.search.Query query=parser.parse("FindMe");
//Convert to a hibernate query.
org.hibernate.search.jpa.FullTextQuery query2=fullTextSession.createFullTextQuery(query, SampleBean.class);
//Set the projections
query2.setProjection("id");
//Run the query.
for (Object[] row:(List)query2.getResultList()){
//Show the list of id's
System.out.println(row[0]);
}
//Close
em.getTransaction().commit();
em.close();
emf.close();
query2 does the projection and all is well!

Related

Difference between hibernate query api and criteria api [duplicate]

Can anyone please tell me the difference between Hibernate's:
createCriteria
createQuery
createSQLQuery
Can anyone tell me what data these three functions return, c.q. direct me to a proper and simple link to study these Hibernate functions?
To create query in the Hibernate ORM framework, there is three different types. The following are the three ways to create query instance:
session.createQuery()
session.createSQLQuery()
session.createCriteria()
Look into the details of each category in detail.
Session.createQuery()
The method createQuery() creates Query object using the HQL syntax. For example:
Query query = session.createQuery("from Student s where s.name like 'k%'");
Session.createSQLQuery()
The method createSQLQuery() creates Query object using the native SQL syntax. For example:
Query query = session.createSQLQuery("Select * from Student");
Session.createCriteria()
The method createCriteria() creates Criteria object for setting the query parameters. This is more useful feature for those who don't want to write the query in hand. You can specify any type of complicated syntax using the Criteria API.
Criteria criteria = session.createCriteria(Student.class);
1. session.createQuery()-> Can create query using HQL and can perform CRUD Operations
Example:
Query query = session.createQuery("from Student");
List list=quey.list();
Query query = session.createQuery("update Student where studentid=9");
int result=query.executeUpdate();
Query query = session.createQuery("delete Student where studentid="+ studentId);
int result=query.executeUpdate();
Query query = session.createQuery("insert into Student where studentid="+ studentId);
int result=query.executeUpdate();
session.createSQLQuery()-> Can create query using SQL and can perform CRUD Operations
session.createCriteria()->Can create query using Criteria API and can perform only Read Operations
------------------------
PERSON
------------------------
**DB_Column**| **POJO**
PERSON_ID | personID
------------------------
createQuery()
you are using pojo fields. Using HQL syntax.
Query query = session.createQuery("from Person s where s.personID like 'A%'");
// returns:
List<Person> persons = query.list();
createSQLQuery()
You are using Native|DB fields.
After googling some site, Came to know this will also clear the cache as hibernate don't know the what you have executed.
Query query = session.createSQLQuery("select s.* from Person s where s.person_ID like 'A%'");
// returns:
List<Object[]> persons = query.list();.
createCriteria()
Create sql query using Criteria object for setting the query
parameters.
Useful when switching DB.
Read only query
Criteria criteria = session.createCriteria(Person.class);
criteria.add(Restrictions.like("personId", "A%"));
List<Person> persons = criteria .list();
createSQLQuery -- is for native sql querying which is selected by you with jdbc driver cfg or something else.
createQuery -- is for hibernate querying which provides you independent querying which makes you run that on many databases using API and more other advantages.
createCriteria -- is better to use for simple querying on db because of it's simplicity.
I hope this helps you!

How does Hibernate generate sql string from session.get queries

I am using Hibernate 4.2.4 and I am interested to know how Hibernate translate a session.get call to an equivalent sql query that is eventually used to retrieve rows from database. I do not want to log the generated sql in console. I want to use the same sql query in my application. Something like below.
...
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.buildServiceRegistry());
// I want the query string here
String query = sessionFactory.someUnknownMethod(Some Paramters);
Session session = sessionFactory.openSession();
// actual session.get query
Comment comment = (Comment) session.get(Comment.class, new Integer(1));
...
I have seen this thread for Criteria query -> How to get SQL from Hibernate Criteria API (*not* for logging).
I would like to know if similar procedure exists for session.get type queries.
I have also seen this thread -> get SQL from hibernate get
where the question is exactly same as mine, but the accepted solution talks about fetching statistics which, to my understanding, only accounts for the queries that have already been executed. Plus, from statistics I was able to catch hql/sql queries but not session.get queries.
I want to know if there is a way for a user to generate and use the sql even before the actual session.get gets executed (possibly by following the same path as hibernate).

Delete data from JPA without using SQL

im familiar with this following way to delete the data (just the data ,not the entity itself)
from the entity
entityManager.getTransaction().begin();
entityManager.createQuery("DELETE FROM " + className)
.executeUpdate();
entityManager.getTransaction().commit();
there is another way to do that like to provide the entityname and then reomve all the data .
You're not using SQL in your code but JPQL, JPA Query Language.
There is no other way to delete all data at once, except by loading all of them and deleting them one by one. It's not even possible with criteria queries since they don't support delete operation yet.
Well.. in this case both NativeSQLQuery and JPQL resolve to the same thing. What you did is JPQL way. The following you could write a nativeSQLQuery
EntityManager em = ...;
Query query = em.createNativeQuery ("SELECT * FROM EMP", Employee.class);

hibernate - get named query string without session

Using a Session a named query can be retrieved like following:
Query query = session.getNamedQuery(queryName);
But how can a named query be retrieved without using a session?
I am modifying the query-string dynamically and don't need a Session at that moment.
The defined named-query is not changed
SessionFactoryImplementor sesionFactoryImplementor=(SessionFactoryImplementor)sessionFactory;
sesionFactoryImplementor.getNamedQuery("test").getQueryString();
Works with Hibernate 4. As Nayan Wadekar, commented you can not modify it at runtime.
This works well for me:
Query query = em.createNamedQuery(namedQuery);
String hql = query.unwrap(org.hibernate.Query.class).getQueryString();
Hope this helps!

Delete Derby entries

I use JPA to add data to Derby DB with eclipse link and when there is duplicated ID.
I got error, there is a way in run-time (with code) to simple delete all the table entries.
I don't need the old entry just new entries in every time that I invoke the program.
I tried with
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager entityManager = factory.createEntityManager();
entityManager.getTransaction().begin();
Query query = entityManager.createQuery("SELECT p FROM Job p ");
List resultList = query.getResultList();
for (Object result : resultList) {
entityManager.remove(result);
}
entityManager.getTransaction().commit();
entityManager.close();
but here I use query before and I don't want to do that I want to delete all the entries and I don't care what is there before.
You can use the SQL DELETE query at runtime everytime the application starts. If you don't post some code, we can't help.
EDIT :
You can execute the query as follows in some earlier transaction or the same transaction before the query:
int deletedCount = entityManager.createQuery("DELETE FROM Job").executeUpdate();
You could either execute a delete query, or configure your persistence unit to recreate the tables when the persistence unit is deployed.
See,
http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/p_ddl_generation.htm#BABHEJJI

Categories

Resources