hibernate - get named query string without session - java

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!

Related

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);

Putting external properties into named queries

Does anyone know of a way, if any, to put an external property into a jpa named query?
So for example:
#NamedQuery(name = "Test", query = "select t from ${table.name} t")
As opposed to:
#NamedQuery(name = "Test", query = "select t from TableName t")
Thanks
Annotations are final hence they cannot be changed at runtime, so you cannot do that.
You could define the native query at runtime instead of as a named query and translate the SQL string yourself.
Other solution would be to use some sort of pre compiler on your code, or use some sort of persistence unit event to post process your queries. If you are using EclipseLink, you could use a SessionCustomizer for this, or a SessionEventListener to pre process SQL queries before they are executed.

Java query db issues. using hibernate and struts2

I am getting into java here. Fun and frustrating all at the same time :)
I have a simple method called showUsernames():
public String showUsernames(){
TimesheetUserDAO su = new TimesheetUserDAO();
Session session = su.getSession();
setUsers(su.findByUsername(_users));
session.close();
return SUCCESS;
}
...however, I am having a time getting just the usernames out of the database. It is possible with the Hibernate DAO to get this correct? I am able to use su.findAll() and return everything.
Any thoughts? Need more code? Thanks :)
The DAO probably executee a request like
select u from User u where ...
Change the query to
select u.name from User u where ...
Of course, instead of having a List<User> as a result, you'll have a List<String>.
This is basic stuff described in the Hibernate reference documentation. Have you read it?
Also, getting the session from the DAO and closing it manually like this shows a design problem. This should be encapsulated by the service layer or, even better, by the declarative transaction handling.

Hibernate createNativeQuery using IN clause

Using Java, Hibernate.
I have a query
String pixIds = "1,2,3";
String query = "SELECT * FROM comment WHERE PIX_ID IN (:pixIds)";
q.setParameter("pixIds", pixIds);
List<Object[]> results = q.getResultList();
I'm not able to bind this parameter to pixIds using the code above. What is the right way to do this?
Note : the query I have here is a simplified version of my actual query.
The following method works
public Query setParameterList(String name, Collection vals) throws HibernateException
Hibernate doesn't support binding collection to IN (...) in SQL queries.
You need to work the same way as with plain JDBC: given a collection, dynamically generate a query with appropriate number of ?s in IN clause, and then bind elements of that collection to ?s.

Categories

Resources