Getting the JPQL/SQL String Representations for a Criteria Query - java

How to Getting the SQL String Representations for a Criteria Query with parmetervalue ?
I tried this but it returns a string to me without the parameter values:
String QueryString = 'SELECT * FROM CUSTOMERS WHERE lastname = ?'
query = entityManager.createNativeQuery(QueryString);
query.setParameter(1, "toto");
System.out.print(query.unwrap(JpaQuery.class).getDatabaseQuery().getSQLString());
But returns "SELECT * FROM CUSTOMERS WHERE lastname = ?"
instead of "SELECT * FROM CUSTOMERS WHERE lastname = 'toto'"

Thanks to #GrootCfor helping me find the solution.
If it helps other people here is the solution:
String QueryString = 'SELECT * FROM CUSTOMERS WHERE lastname = ?';
Query query = entityManager.createNativeQuery(QueryString);
Session session = entityManager.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery databaseQuery = query.unwrap(org.eclipse.persistence.jpa.JpaQuery.class).getDatabaseQuery();
DatabaseRecord recordWithValues= new DatabaseRecord();
query.setParameter(1, "toto");
recordWithValues.add(new DatabaseField(Integer.toString(1)), "toto");
databaseQuery.prepareCall(session, recordWithValues);
String sqlStringWithArgs = databaseQuery.getTranslatedSQLString(session, recordWithValues);
System.out.print(sqlStringWithArgs);
====SELECT * FROM CUSTOMERS WHERE lastname = 'toto'====

Related

java.lang.IllegalArgumentException: Parameter with that name [xxx] did not exist

java.lang.IllegalArgumentException: Parameter with that name [xxx] did not exist
I'm using Spring-data-jpa + hibernate
String login = "AdanaKebap";
String userQuery = "select * from user where username like '%:login%'"; // not working
Query query = entityManager.createNativeQuery(userQuery);
query.setParameter("login", login);
List<Object[]> userObjects = query.getResultList();
I'd try
String userQuery = "select * from user where username like '%?%'"; // not working
query.setParameter("1", login);
String userQuery = "select * from user where username like '%?1%'"; // not working
query.setParameter("1", login);
String userQuery = "select * from user where username like ':login'"; // not working
query.setParameter("login", login);
String userQuery = "select * from user where username like :login "; // not working
query.setParameter("login", login);
String userQuery = "select * from user where username = :login "; // working, but i don't need this
You need to use CONCAT, to concat % and the value passed to the query, so try :
String userQuery = "select * from user where username like CONCAT('%', ?1, '%')";
//...
query.setParameter(1, login); // note here you have to use the index of placeholder
or
String userQuery = "select * from user where username like CONCAT('%', :login, '%')'";
//...
query.setParameter("login", login);

Pass list of values on query parameter

String hql = "select * from myTable where isActive IN (:isActive)";
Query query = session.createQuery(hql);
query.setString("school","");
query.setString("isActive", "Y");//working
query.setString("isActive", "N");//working
query.setString("isActive", "Y","N"); // not working
query.setString("isActive", "'Y','N'"); // not working
return query.list();
I have no idea if the code below should work, I was wondering if i can pass list of values to my search string parameter so there's no need for me to create to queries ; one for select all data regardless of status and another to select only active data.
Use Query.setParameterList() to pass in a List as a parameter:
String hql = "select * from myTable where isActive IN (:isActive)";
Query query = session.createQuery(hql);
List<String> isActiveList = new ArrayList<>();
isActiveList.add("Y");
isActiveList.add("N");
query.setParameterList("isActive", isActiveList);
return query.list();

Using Select and where statement in Criteria

I am in the process of replacing jdbc with hibernate in my Web Application. I have learned that i don't have to write any SQL queries in this. Instead of this,criteria queries can help me.
These are my SQL queries which i want to convert to hibernate using criteria not HQL.
String getOrgIdQuery = "SELECT * FROM USER_DETAILS WHERE USER_ID= ?";
rsDeptName = stmt.executeQuery("SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID ="+ DeptID + ";");
String insertCreateCdcValuesFirst = ("UPDATE User_Details SET User_Name=?, Organization_ID=?, Department_ID=?, Access_Ctrl = ?, User_Role=? WHERE User_ID = ?;");
First off all you must map your table with POJOS.
String getOrgIdQuery = "SELECT * FROM USER_DETAILS WHERE USER_ID= ?";
Preceding code in Hibernate look like following.
Criteria criteria = session.createCriteria(USER_DETAILS.class);
criteria.add(Restrictions.eq("user_id",yourUserId));
List<USER_DETAILS> list = criteria.list();
Your second select query is also same as preceding.
String insertCreateCdcValuesFirst = ("UPDATE User_Details SET User_Name=?, Organization_ID=?, Department_ID=?, Access_Ctrl = ?, User_Role=? WHERE User_ID = ?;");
With Hibernate Criteria update looks like following:
USER_DETAILS user_details = (USER_DETAILES) session.get(USER_DETAILS.class,yourUserId);
user_details.setUser_Name(NewUserName);
user_details.setOrganization_Id(newOrganizationId);
// some other fields update goes here
session.update(user_details);
tx.commit();
I hope this help you.

How to set placeholders in hibernate

Hi this my java code here am using hibernate to check whether this email id and password exist in db or not could anybody plz exp line me how to place the value to this place holders.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query;
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).list();
ses.close();
Thanks in advance
Try this one.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query = "from RegisterPojo rp where rp.email = :emailAddress and rp.pwd = :password";
List<RegisterPojo> list = ses.createQuery(query)
.setParameter("emailAddress", Your email address)
.setParameter("password", Your password)
.list();
ses.close();
You should use a prepared statement instead of a string. example here
PreparedStatement preparedStatement = con.prepareStatement ("from RegisterPojo where email=? and pwd=?");
preparedStatement.setString(1, "email");
preparedStatement.setString(2, "password");
You have to modify your query like this,
query = "from RegisterPojo where email =:email and pwd =:password ";
List<RegisterPojo> list = ses.createQuery(query)
.setParameter("email",emailVal)
.setParameter("password",emailVal)
.list();
Read the hql docs here
Session ses = HibernateUtil.getSessionFactory().openSession();
String query;
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).setParameter(0,emailVal).setParameter(1,emailVal).list();
ses.close();
Try this one.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query = "from RegisterPojo where email = '" + varEmailAddress + "' and pwd = '" + varPassword + "'";
List<RegisterPojo> list = ses.createQuery(query).list();
ses.close();
Sorry This Is not Answer but instead another case, in above case #Grigoriev Nick suggested
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).setParameter(0,emailVal).setParameter(1,emailVal).list();
but here the script starts with directly from clause while what if I want want to used sql like below
WITH A (
/// do some selection from many tables using various union as per my requirement
),
B (
/// another set of sqls for different set of data
)
select XXX from A a join B b on a.XYZ = b.xyz
where
/// few more fixed where clause conditions
AND A.SOME_COLUMN = ? // Here Instead Of String Concatenation I want to
//use Query parameters but using hibernate instead of raw Prepares statements

Why SQLQuery setParameter cannot use LIKE?

I have here:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME LIKE '%?%'");
query.setParameter(0, personName);
I get the following error:
java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
But when I try:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME = ?");
query.setParameter(0, personName);
its working.
I need to use LIKE.
You can do like this:
Session session = getSession();
SQLQuery query = session.createSQLQuery("SELECT * FROM PERSON WHERE NAME LIKE ?");
query.setParameter(0, "%" + personName + "%");
User criteria as
Criteria criteria = getSession().createCriteria(Person.class);
criteria.add(Restrictions.like("name", personName, MatchMode.ANYWHERE));
criteria.list();
String strQuery = "SELECT * FROM PERSON WHERE upper(NAME) LIKE '%"
+ personName.trim().toUpperCase() + "%'";
Session session = getSession();
SQLQuery query = session.createSQLQuery(strQuery );

Categories