Query using alias on column give an error - java

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)

Related

How can I run this SQL statement with SpringBoot data JPA?

I'm trying to create a data filter using SpringBoot and PostgreSQL, I'm trying to run a query to get a customer by its name or id or account id in a searchBar, running into an issue when running a native SQL statement in Spring Data JPA, I'm getting the following error:
The error says that Could not execute query. I've tried running the statement in different ways but still giving me the error, these are the ways I have tried:
#Query(
value = "SELECT json_data FROM contact WHERE name = :searchText OR account_id = :searchText OR id = :searchText",
nativeQuery = true)
#Query(
value = "SELECT json_data FROM contact WHERE contact.name LIKE %:searchText% OR contact.account_id LIKE %:searchText% OR contact.id LIKE %:searchText%",
nativeQuery = true)
#Query(
value = "SELECT json_data FROM contact WHERE name = ?1 OR account_id = ?1 OR id = ?1",
nativeQuery = true)
Page<Contact> findByWord(Pageable pageable, #Param("searchText") String searchText);
I'm able to run successfully the query in PGAdmin as follows:
SELECT json_data FROM contact
WHERE name = 'TESLA ARQUITECTURA S.A.S'
OR account_id = ''
OR id = ''
or:
SELECT json_data FROM contact
WHERE name = ''
OR contact.account_id = ''
OR contact.id = '2'
or:
SELECT json_data FROM contact
WHERE name = ''
OR account_id = '1674590687S'
OR id = ''
All of these statements are working and the idea is that if I pass as a parameter to the SQL statement it will return the information from the column json_data.
So I'm not sure if im doing something wrong when creating the query in the repository, I would appreciate so much your help on this.
Do select * not select json_data in your query, currently you are trying to map a single column into a whole Entity that's why it's complaining the id is missing from the result set. column name seq_id was not found in this result set was there in the error log all along.

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

JPA native sql query mapping error?

I have a JPA entity MyEntity which includes a composite primary key in a #Embeddable class MyEntityPK.
I am using a native sql query in method getThreeColumnsFromMyEntity():
public List<MyEntity> getThreeColumnsFromMyEntity() {
List<MyEntity> results = em.createNativeQuery("select pid,name,dateofbirth from (select pid,name, dateofbirth,max(dateofbirth) "
+ "over(partition by pid) latest_dateofbirth from my_entity_table) where"
+ " dateofbirth = latest_dateofbirth;","myEntityMapping").getResultList();
return results;
My #SqlResultSetMapping:
#SqlResultSetMapping(
name = "myEntityMapping",
entities = {
#EntityResult(
entityClass = MyEntityPK.class,
fields = {
#FieldResult(name = "PID", column = "pid"),
#FieldResult(name = "NAME", column = "name")}),
#EntityResult(
entityClass = MyEntity.class,
fields = {
#FieldResult(name = "dateofbirth", column = "dateofbirth")})})
My JPA columns are named : #Column(name="DATEOFBIRTH"), "PID" and "NAME".
I tested my sql statement straight on the db and it works fine.
When i run it on Eclipse I get an Oracle error:
ORA-00911 and "Error code 911 , Query: ResultSetMappingQuery [..]
My guess is there is something wrong with the mapping but I cannot find out what it is.
I assume you get this error because you are missing the alias name for the subquery, so instead you can try this :
select
pid,
name,
dateofbirth
from
(
select
pid,
name,
dateofbirth,
max(dateofbirth) over(partition by pid) AS latest_dateofbirth
from
my_entity_table
) second_result
-- ^--------------- use an aliase name to the subquery
where
second_result.dateofbirth = latest_dateofbirth
-- ^----use the aliase name to reference to any of its fields, in your case 'dateofbirth'
Take a look about the error meaning here ORA-00911: invalid character tips

Hibernate Query Language (HQL) Update list

I'm using Hibernate and I want to make a bulk update, changing the status of all objects within a list of ids.
So I tried:
String update = "UPDATE Foo as foo SET foo.status = :status WHERE foo.id in (:idList)"
Which caused an exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax;
I also tried:
String update = "UPDATE Foo as foo SET foo.status = :status WHERE foo.id in (SELECT id FROM Foo WHERE id in (:idList))"
That caused the same exception.
I'm inserting the parameters like this:
StatelessSession ss = sessionFactory.openStatelessSession();
Query query = ss.createQuery(update);
query.setParameter("status", status);
query.setParameterList("idList", ids);
query.executeUpdate();
Any ideas how to make this work?
Thanks in advance
Status is a MySQL reserved word. Rename your column to something else

How to pass parameter on jpa query?

I have two entities Like SmsOut and SmsIn. The relation between two entities contains OneToMany where smsIn.id is primary key and smsOut.sms_in_id is foreign key.
Now I want to pass parameter like smsIn.mobileNumber, smsIn.smsText and so on, on the query
SELECT so FROM SmsOut so order by id desc
Following is my database diagram:
Edited
Following is my code :
String sql = "SELECT so FROM SmsOut so WHERE so.smsInId.mobileNumber =:mobileNumber AND so.smsInId.smsText =:smsText AND so.smsInId.shortCode =:shortCode between so.smsOutDate =:startDate and so.smsOutDate =:endDate order by id desc";
Query query = em.createQuery(sql);
query.setParameter("mobileNumber", mobileNumber);
query.setParameter("smsText", smsText);
query.setParameter("shortCode", shortCode);
query.setParameter("smsOutDate", startDate);
query.setParameter("smsOutDate", endDate);
smsOutList = query.getResultList();
and exception is :
SEVERE: line 1:188: expecting "and", found '='
java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: expecting "and", found '=' near line 1, column 188 [SELECT so FROM com.f1soft.SMSC.entities.SmsOut so WHERE so.smsInId.mobileNumber =:mobileNumber AND so.smsInId.smsText =:smsText AND so.smsInId.shortCode =:shortCode between so.smsOutDate =:startDate and so.smsOutDate =:endDate order by id desc]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:624)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:96)
Please Help me.
Thanks
You haven't explained the JPA relationship between SmsIn and SmsOut, so I'll assume SmsOut has a getSmsIn() with a relation on the id field.
When you have an EntityManager em, you can call em.createQuery, which is like SQL prepare, and then setParameter:
TypedQuery<SmsOut> q = em.createQuery("SELECT so FROM SmsOut so WHERE so.smsIn.mobileNumber = :number ORDER BY id DESC");
q.setParameter("number", "12345678");
List<SmsOut> results = q.getResultList();
See the Javadoc for Query for the different ways you can specify the parameters.
SELECT so FROM SmsOut so WHERE smsIn.mobileNumber = ? AND smsIn.smsText =? order by id desc
Replace the ? sign with the apropiate values.
between is the problem:
between so.smsOutDate =:startDate and so.smsOutDate =:endDate
try
so.smsOutDate between =:startDate and =:endDate

Categories

Resources