jpa native query control entity(part 3) - java

Retrieve company table
GetEntity.java
String table = "company";
String q = "select * from " +table;
Query query = em.createNativeQuery(q, Company.class);
List<Company> list = query.getResultList();
...
Retrieve staff table
GetEntity.java
String table = "staff";
String q = "select * from " +table;
Query query = em.createNativeQuery(q, Staff.class);
List<Staff> list = query.getResultList();
...
My questions is how do I control the ? from the following:
em.createNativeQuery(q, ?);
List<?> list = q.getResultList();
Any ideas or suggestion?

Another option is to pass the Class entityClass as an argument to your find method and then you can try and derive table name from entityClass by using reflection and use the entityClass as the type argument to your createNativeQuery method.
Hope this helps!

Related

Select table row using HQL with param

I want to use this HQL query in order to select table row value:
String hql = "select e.token, e.name from Terminals e where e.token = ?";
Terminals terminal = entityManager
.createQuery(hql, Terminals.class)
.setParameter(0, terminalToken)
.getSingleResult();
But I get this result:
java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [org.api.entity.Terminals]
What is the proper way to implement this?
Your query return two Objects token and name and not a Terminals Object.
Instead you can use :
Object[] obj = entityManager
.createQuery(hql)
.setParameter(0, terminalToken)
.getSingleResult();
if(obj != null){
Terminals terminal = new Terminals((String) obj[0], (String) obj[1]);
}
Or you can create a constructor in Terminals class which hold two fields :
public Terminals(String token, String name){
this.token = token;
this.name = name;
}
then change your code to be :
String hql = "select new com.package.Terminals(e.token, e.name) from Terminals e where e.token = ?";
Terminals terminal = entityManager
.createQuery(hql, Terminals.class)
.setParameter(0, terminalToken)
.getSingleResult();
IMO, you should not directly call createQuery to assign to a custom object. And there is a possiblity of returning a list.
Query query = entityManager.createQuery(hql).setParameter(0, "something");<br>
List<Object[]> terminals = query.getResultList();
and retrieve the objects with an index as the ff as an example:
StudentDto dto = new StudentDto();
for(Object[] a: std) {
dto = new StudentDto();
dto.setId((long) a[0]); //id
dto.setName(a[1].toString()); //first name
dto.setPassportNumber(a[2].toString()); //last name
}

Query not giving solution in DAO class

when i run my query in database visualizer its working perfectly, but i think there are some issues in syntax when i convert it in my DAO class method.
I want to get whole data against the name provided
In Visualizer:
SELECT first_name,last_name,nic,phone,email FROM x_hr_user where (first_name = 'Irum');
Now in Dao
public List<XHrUser> findXHrUserByNameInTable()
{
String name ="Irum";
Query query = em.createQuery("SELECT xHrNewUserObj.firstName,xHrNewUserObj.lastName, xHrNewUserObj.nic, xHrNewUserObj.phone, xHrNewUserObj.emil FROM XHrUser xHrNewUserObj where (xHrNewUserObj.firstName) = (name)");
List<XHrUser> list = query.getResultList();
return list;
}
Instead of showing single row, it displays whole data Table
Thank you
Your current query is not valid JPQL. It appears that you intended to insert the raw name string into your query, which could be done via a native query, but certainly is not desirable. Instead, use a named parameter in your JPQL query and then bind name to it.
String name = "Irum";
Query query = em.createQuery("SELECT x FROM XHrUser WHERE x.firstName = :name")
.setParameter("name", name);
List<XhrUser> list = query.getResultList();
You have to write query as below. where : is used for variable
Query query = em.createQuery("SELECT xHrNewUserObj.firstName,xHrNewUserObj.lastName, xHrNewUserObj.nic, xHrNewUserObj.phone, xHrNewUserObj.emil FROM XHrUser xHrNewUserObj where (xHrNewUserObj.firstName) = :name");

Set list parameter to native query

I would like to set parameter to a native query,
javax.persistence.EntityManager.createNativeQuery
Something like that
Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN ?");
List<String> paramList = new ArrayList<String>();
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter(1, paramList);
Trying this query result in Exception:
Caused by: org.eclipse.persistence.exceptions.DatabaseException:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near
'_binary'??\0♣sr\0‼java.util.ArrayListx??↔??a?♥\0☺I\0♦sizexp\0\0\0☻w♦\0\0\0t\0
f' at line 1
Error Code: 1064
Call: SELECT * FROM Client a WHERE a.name IN ?
bind => [[firstValue, secondValue]]
Query: ReadAllQuery(referenceClass=TABLE_A sql="SELECT * FROM TABLE_A a WHERE a.name IN ?")
Is it any way to set list parameter for native query, without cast to string and append it to sql query?
P.S. I'm use EclipseLink 2.5.0 and MySQL server 5.6.13
Thanks
I believe you can only set list parameters to JPQL queries, not native queries.
Either use JPQL, or construct the SQL dynamically with the list.
It works if you name the parameter:
Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN (:names)");
List<String> paramList = new ArrayList<String>();
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter("names", paramList);
Not a solution but more of a workaround.
Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN ?");
List<String> paramList = new ArrayList<String>();
String queryParams = null;
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter(1, paramList);
Iterator<String> iter = paramList.iterator();
int i =0;
while(iter.hasNext(){
if(i != paramList.size()){
queryParams = queryParams+ iter.next() + ",";
}else{
queryParams = queryParams+ iter.next();
}
i++;
}
query.setParameter(1, queryParams );
You can add multiple values like this example:
TypedQuery<Employee> query = entityManager.createQuery(
"SELECT e FROM Employee e WHERE e.empNumber IN (?1)" , Employee.class);
List<String> empNumbers = Arrays.asList("A123", "A124");
List<Employee> employees = query.setParameter(1, empNumbers).getResultList();
Source: PRAGT E., 2020. JPA Query Parameters Usage. Retrieved from: https://www.baeldung.com/jpa-query-parameters

Hql Query to Bind a Data Member

Query qry = session.createQuery("From RegistrationBean where ? = ?");
qry.setString(0,searchCriteria);
qry.setString(1,searchField);
searchList =(ArrayList<RegistrationBean>) qry.list();
RegistrationBean Entity class has userName, address, age fields..
I want to search a user by search criteria such as userName, address etc. using the above single query...
But the query is returning me zero results even though the user exist..
what's the problem?
Both parameters are set to 0 position, the second is not set. The position parameter should be set sequentially.
qry.setParameter(0,searchCriteria);
qry.setParameter(1,searchField);
But the field name should pass in the following way
String queryString = "from RegistrationBean as model where model." + propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
Try in the following way:
Query qry = session.createQuery("select * from RegistrationBean where :searchCrit = :searchValue");
qry.setString(":searchCrit",searchCriteria);
qry.setString(":searchValue",searchField);
searchList =(ArrayList<RegistrationBean>) qry.list();
It is more appropriate to use it like this instead of setting indexes (your problem is that you set both to 0), because if you change something in your query you might need to change your setters afterwards.

HIbernate query

I want to execute a query using hibernate where the requirment is like
select * from user where regionname=''
that is select all the users from user where region name is some data
How to write this in hibernate
The below code is giving result appropraitely
Criteria crit= HibernateUtil.getSession().createCriteria(User.class);
crit.add(Restrictions.eq("regionName", regionName));
Well as you alaready said you can either use the Criteria API or create a HQL query:
// Criteria
List<User> users = HibernateUtil.getSession().createCriteria(User.class);
crit.add(Restrictions.eq("regionName", regionName)).list();
// HQL
String query = "SELECT FROM User WHERE regionName = :region";
List<User> users = HibernateUtil.getSession().createQuery(query).setString("region", regionName).list();
String hql = "SELECT u FROM User u WHERE regionName=:regionName";
Query q = session.createQuery(hql);
q.setParameter("regionName", regionName);
List result = q.list();

Categories

Resources