cast from Object to Class : failed - java

I get this error
Exception in thread "main" java.lang.ClassCastException:
[Ljava.lang.Object; cannot be cast to xxx.xxx.xxx.Terminal
when i try this code; so what is wrong ??
for(int k=0;k<argTerminal.length;k++){
String hql = "select crimpkontakt from Terminal where id="+argTerminal[k];
Query query = session.createQuery(hql);
query.setMaxResults(1);
Terminal nameTerminal = (Terminal) query.uniqueResult();

If you want to select Terminal object your HQL should look like:
String hql = "from Terminal where id="+argTerminal[k]
Also in order to avoid SQL injection using parameters API is a preferred option:
Query query = session.createQuery("select from Terminal where id = :id");
query.setString("id", argTerminal[k]); // I assume that id is a String here
query.setMaxResults(1);
Even better if id is a primary key you can use session.get(Terminal.class, argTerminal[k])

Related

Getting an error while using "Generics" in Hibernate Query

I'm using Hibernate in my project and using "Query" Like below.
Query query = em.createQuery("delete from User where name=:name");
query.setParameter("name", "Zigi");
int deleted = query.executeUpdate();
I'm getting the result. When i'm using generics Like below
Query<?> query = em.createQuery("delete from User where name=:name");
query.setParameter("name", "Zigi");
int deleted = query.executeUpdate();
getting the result because "?" is something as wildcard (or) it will accept any datatype
when i'm using the code as below getting some error( java.lang.IllegalArgumentException: Update/delete queries cannot be typed ). i'm using Integer datatype because createQuery return number when it's executed
Query<Integer> query = em.createQuery("delete from User where name=:name", Integer.class);
query.setParameter("name", "Zigi");
int deleted = query.executeUpdate();
Any suggestions. I have to use Generics with specific datatype in it like above code.
thanks in advance
Unfortunately executeUpdate does not allow you to use a typed query.
Instead you can use uniqueResult, and cast to the type that you want:
Query query = em.createQuery("delete from User where name=:name");
query.setParameter("name", "Zigi");
int deleted = (Integer) query.uniqueResult();
Referencing this answer

How to fetch data from joined tables straight to a class?

Is it possible to retrieve data from a query straight into the EmployeeForm?
Query as stored procedure empdata
SELECT a.name,b.username,b.password FROM Tbemployee left join Tbuser
Code
List<EmployeeForm> form = new ArrayList<EmployeeForm>();
EmpDB service = (EmpDB) RuntimeAccess.getInstance().getServiceBean(
service.begin();
Session session = service.getDataServiceManager().getSession();
SQLQuery query = session.createSQLQuery("EXEC empdata");
List list = query.list();
formList = list;
This gives me an error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.emp.form.EmployeeForm
You need to use a ResultTransformer
The other option is to cast to List<Object[]> which contains rows with columns from the query result, and then iterate and extract data(more work).
The transformer could be something like:
query.setResultTransformer(Transformers.aliasToBean(EmployeeForm.class));

HQL: Handling special characters

I am trying to fetch value from database using HQL but am getting exceptions because value contains special characters. I am not able to figure out why.
Below is the code i am trying:
HotelMapping hotelMapping = null;
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.getTransaction();
tx.begin();
String hotelName = "A Fisher's Inn Motel";
Query query = session.createQuery("from HotelMapping hm where hm.hotelID.hotelName='"+hotelName+"'");
HotelMapping mapping = query.uniqueResult();
}
tx.rollback();
sessionFactory.close();
The pojos look like below:
Hotel.java
public class Hotel{
String hotelName;
double price;
//getters and setters
}
HotelMapping.java
public class HotelMapping{
#OneToOne(cascade = CascadeType.ALL)
Hotel hoteID
String location;
}
The query string
Query query = session.createQuery("from HotelMapping hm where hm.hotelID.hotelName='"+hotelName+"'"); gives me below exception :
Exception in thread "main" org.hibernate.QueryException: expecting ''', found '<EOF>' [from com.pb.model.HotelMapping hm where hm.hotelID.hotelName='A Fisher's Inn Motel']
I tried escaping the apostrophe but with no luck. I ven tried setting the query parameter but again i got exception
query.setParameter("hotelName", "A Fisher's Inn Motel");
It says Exception in thread "main" org.hibernate.QueryParameterException: could not locate named parameter [hotelName]
Please if someone could help me achieving a generalized solution for the special character handling?
You should never use concatenation to pass dynamic parameters like this. This is not only not efficient, but also not robust (since a single quote in the parameter value makes the query invalid) and insecure, since a malicious user could pass a value that changes the semantics of the query (google for "SQL injection attack").
Instead, use parameters:
Query query = session.createQuery(
"from HotelMapping hm where hm.hotelID.hotelName = :hotelName");
query.setString("hotelName", hotelName);

Hibernate query giving java.lang.IllegalArgumentException: node to traverse cannot be null

This simple query
session = com.jthink.songlayer.hibernate.HibernateUtil.getSession();
Query q = session.createQuery("recNo from SongChanges");
giving this stacktrace
java.lang.IllegalArgumentException: node to traverse cannot be null!
at org.hibernate.hql.internal.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:63)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:272)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:119)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:214)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:192)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1537)
if I do
session = com.jthink.songlayer.hibernate.HibernateUtil.getSession();
Query q = session.createQuery("from SongChanges");
I dont get the error, but I only need the recNo
Any ideas ?
You forgot the select:
Query q = session.createQuery("select sc.recNo from SongChanges sc");
This error also commonly happens when you use the method createQuery to run a named query, instead of getNamedQuery, for example:
session.createQuery("InvoiceItem.itemsFromInvoice")
when the correct approach would be
session.getNamedQuery("InvoiceItem.itemsFromInvoice")
The SELECT clause provides more control over the result set than the from clause. If you want to obtain few properties of objects instead of the complete object, use the SELECT clause. Following is the simple syntax of using SELECT clause to get just name field of the Employee object:
String hql = "SELECT E.name FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();
If you want whole object that time "select * from" is not needed.

Query using alias on column give an error

When i use alias for column i get error. Without alias everytinig works good. What is the problem with that ? This is simple example, but need to use more aliases in real project to wrap results in some not-entity class, but can't because of this error. How to solve this ?
NOT WORKING (with alias on id column):
public List<Long> findAll(Long ownerId) {
String sql = "select id as myId from products where ownerId = "+ownerId;
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
}
Error:
WARN [JDBCExceptionReporter:77] : SQL Error: 0, SQLState: S0022 ERROR
[JDBCExceptionReporter:78] : Column 'id' not found.
WORKING (without alias):
public List<Long> findAll(Long ownerId) {
String sql = "select id from products where ownerId = "+ownerId;
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
}
If your "product" is mapped, hibernate probably don't know about "myId" and therefore can't select it.
You can try something like:
getSession().createSQLQuery(sql).addScalar("myId", Hibernate.LONG)

Categories

Resources