Update single column field in table using Hibernate query - java

I am trying to update the single value in table (without updating any others) by using Hibernate.
Here is my code:
#Override
public void updateUser(User userDetails){
Query query = session.createQuery("UPDATE User u set u.balance = :balanceValue where u.userId = :userIdValue AND c.userType = :userTypeValue");
query.setParameter("balanceValue", userDetails.getBalance());
query.setParameter("userIdValue", userDetails.getUserId());
query.setParameter("userTypeValue", userDetails.getUserType());
query.executeUpdate();
}
Please note that all parameters I am inserting are String. Columns u.userType and u.userId are composite keys.
Caused by: java.sql.SQLException. Incorrect syntax near the keyword
"IN".
I have spent hours on understanding what is wrong with this query. I am using "User" entity for save, update criteria (writing all fields) and delete row without any problems. Thank you in advance for any help.

Related

Update one single column in database using JPQL

How to write a JPQL query to update a single column in MySql DB :
Regular SQL update query :
Update NATAddress SET ordinal = ? WHERE ordinal = ? AND natId = ?
JPQL update query :
UPDATE NATAddress na SET na.ordinal = ?1 WHERE na.ordinal = ?2 AND na.networkDomain.natId =?3
Eclipse shows following error for above JPQL update query
Input parameters can only be used in the WHERE clause or HAVING clause of a query.
Looks like JPA specifications doesn't allow to set input parameters in update columns.
Is there any other way to update other than updating the whole JPA Entity using merge() method?
Update your query to be like this I assume this is the Class name and this is the name of its attributes
UPDATE NATAddress na SET na.ordinal = ? WHERE na.ordinal = ? AND na.networkDomain.natId =?
try this
String query = "Update NATAddress SET ordinal = '"+Parameter1+"' WHERE ordinal = '"+Parameter2+"' AND natId = '"+Parameter3+"'";

Could hibernate be causing this 'fetch out of sequence' error?

I am attempting to execute this query (in an Oracle DB) with Hibernate/Spring JPA:
#Query( value = "DELETE from MY_TABLE where ID = :ID", nativeQuery = true)
void delete(Long ID);
There is a BEFORE DELETE trigger on the table that is making up for poor table design that I cannot change, it runs around deleting rows from dependent tables so that the base DELETE doesn't cause any foreign key errors. I am fairly sure this shouldn't be an issue, but if it is let me know.
Now then, on execution this query causes a ORA-01002: fetch out of sequence error which, according to google, is caused when a fetch has been attempted from a cursor which is no longer valid. (To be completely clear, I have not initiated any cursors with my query or my trigger)
BUT, the row and all its dependants are actually being deleted successfully. Because of this I am not sure what is causing the error and would like yalls' help
The method should be :
#Modifying
#Query( value = "DELETE from MY_TABLE where ID = :ID", nativeQuery = true)
void delete(#Param("ID") Long ID);
Try this and check if the issue still exists.

How to force Hibernate use AND in update query?

I am trying to update a raw by composite primary key by using hibernate.
Hibernate uses the next style for such updates:
update mytable set mycolumn=321 where (left_pk, right_pk) = (123, 456);
Is it possible to force hibernate to use the next style?:
update mytable set mycolumn=321 where left_pk = 123 and right_pk = 456;
Both queries work but with a huge difference (at least in MariaDB).
If we use repeatable read transaction then the first query locks the whole table for updates and the second query locks only the single row for updates.
I would prefer to lock only a single row, so I need to use the second query.
You can go for NamedQueries approach in Hibernate,
For example:
//Create Query
#NamedQueries({ #NamedQuery(name = " YOUR QUERY NAME",
query = "from DeptEmployee where department = :department and emp = :emp") })
// set multiple parameters
query.setParameter("department",department)
.setParameter("emp", emp)
Try giving this a shot.

Java Hibernate : Update most recent entry in MySql database

This is my requirement. I have a bunch of rows with similar data. I want to update some columns on the LATEST entry. So I have written a hibernate query which goes like this
String hql = "UPDATE Studenttable T set T.timestamp=:time,T.Action=:action where T.StudentId=:studentId and T.teacherId=:TeacherId order by T.teacher_student_mapping_id DESC";
Query query = session.createQuery(hql);
query.setParameter("time",time);
query.setParameter("studentId", studentId);
query.setParameter("TeacherId", teacherId);
query.setParameter("action", action);
query.setMaxResults(1);
query.executeUpdate();
What this does is it updates all the rows which satisfies the condition and then returns the latest row. Instead I want it to fetch the latest row satisfying the conditions, and then update it. How can I do it? Any help is deeply appreciated.
P.S. the teacher_student_mapping_id is an auto-generated value, which is also a primary key.
Time is the current time.
Please don't try to make sense of the table, I have changed the names of the columns for confidentiality.
try
String hql = "UPDATE Studenttable T set T.timestamp=:time,T.Action=:action where T.StudentId=:studentId and T.teacherId=:TeacherId order by T.timestamp DESC LIMIT 1";
Since tagged hql you can try something like below. Updating only the latest one based on pk.
UPDATE Studenttable T set T.timestamp=:time,T.Action=:action where T.StudentId=:studentId and T.teacherId=:TeacherId
and T.pk = (select max(tb.pk) from Studenttable tb where tb.StudentId=:studentId and tb.teacherId=:TeacherId )

What's the fastest way to check if a row exists in DB using Hibernate & spring?

I need to check if a row exists in a database in a very fast way.
Let's say I've got the primary key.
I found this code snippet in Hibernate's FAQ website:
Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();
I just started using spring, so I have HibernateTemplate object injected into my class.
How do I translate this snippet to work with HibernateTemplate.
Does anyone knows a better/faster way than this ?
Thanks.
Long count = hibernateTemplate.execute(new HibernateCallback<Long>() {
#Override
public Long doInHibernate(Session session) {
return (Long) session.createQuery("select count(someEntity.id) from SomeEntiuty someEntity ...").uniqueResult();
}
});
Hibernate used Integer for count queries before, but now uses Long. Also, note that even if not deprecated, Spring recommends not to use HibernateTemplate anymore and use the Hibernate API directly (using sessionFactory.getCurrentSession()).
Fastest way of checking primary key exist or not in database.
public void exist(Long id) {
Session session = sessionFactory.getCurrentSession();
String queryString = "select 1 from Employee e where e.id= :id";
Query query = session.createQuery(queryString);
query.setParameter("id", 1l);
Integer result = (Integer) query.uniqueResult();
System.out.println(result);
}
Again this also depends on a lot on what engine that you are using MyISAM vs innodb.
select count(col1) from table; will return the number of rows where the column is not null.
select count(*) from table; will return the number of rows.
Depending upon the database that you are using , a select count(*) will be more expensive than reading it from meta data table or system level tables that keep track of the row count.
Just my 2 cents.
Depending upon various other factors like indexes and other information / joins / access privileges this may be faster
SELECT table_rows FROM `information_schema`.`TABLES` where table_schema = 'database_schema_name' and table_name = 'table_name';
I think it's better to get an specific representative field of the first row found (using the PK or at least another indexed field), than counting all of the possible records that would match your search criteria.
If you're using Spring it will throw EmptyResultDataAccessException if no record was found.

Categories