How to build valid HQL string, which is equivalent to
UPDATE table SET field = null WHERE ....
Do you mean bulk HQL update? Try this
UPDATE myEntity e SET e.myProperty = null WHERE ...
You can also use a parameterized version of the above
UPDATE myEntity e SET e.myProperty = :param WHERE ...
In your code:
int updatedEntities = session.createQuery(updateQueryHQL)
.setString( "param", myValue ) // or .setString( "param", null )
.executeUpdate();
See documentation for details.
If you're not doing bulk updates, you should just set your property to NULL and persist the entity normally.
Why does your update statement need to be done in HQL? Do you have this table mapped to an entity in the system? If you do, then you can simply set the property that maps to that column to null, and run a save on that entity. eg.
myObject.setMyProperty(null);
getSessionFactory().getCurrentSession().save(myObject);
That should work for you, but you gotta have an entity mapped to the table in question.
Related
I want to insert the default value from database when my field is null. I use an Oracle Database.
CREATE TABLE "EMPLOYEE"
("COL1" VARCHAR2(800) NOT NULL ENABLE,
"COL2" VARCHAR2(100) DEFAULT NOT NULL 'toto',
CONSTRAINT "PK_EMPLOYEE" PRIMARY KEY ("COL1")
with a simple SQL request, we can write:
insert into EMPLOYEE(COL1,COL2) values ('titi', default)
How can i do this with annotations MyBatis in Spring? I must create an HandlerType?
In mapper XML, build dynamically the SQL (add the col2 column and value when not null):
insert into employee (col1<if test="col2 != null">, col2</if>)
values (#{COL1}<if test="col2 != null">, #{col2}</if>)
EDIT: since value in annotation must be constant, I used to think dynamic SQl was not possible in annotation, but there is a trick I have found here: How to use dynamic SQL query in MyBatis with annotation(how to use selectProvider)? and checked it myself.
To use dynamic SQL this into an annotation, surround it with "script" tags:
#Insert("<script>insert into employee (col1<if test='col2 != null'>, col2</if>)
values (#{COL1}<if test='col2 != null'>, #{col2}</if>)</script>")
In tests, just escape double quotes " or replace them with simple quotes '
It should work if you omit the COL2 in your colum definition of the insert statement. Because the DB recognizes, that there is no value for the new row and it will apply the default value from the create table statement.
Have you tried something like this?
public interface EmployeeDAO {
String INSERT = "insert into employee (col1) values (#{COL1})";
#Insert(INSERT)
public int insertDefault(PersonDO p) throws Exception;
}
I have added two columns in the sql to get the values through hibernate.My databse is oracle and those fields datatype i number. So i have created the beans with long and (tried Integer too) but when retrieving the values(executing the valuesquery).
Its giving me an error
org.hibernate.type.LongType - could not read column value from result set
java.sql.SQLException: Invalid column name
at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3711)
at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:2806)
at oracle.jdbc.driver.OracleResultSet.getLong(OracleResultSet.java:444)
at weblogic.jdbc.wrapper.ResultSet_oracle_jdbc_driver_OracleResultSetImpl.getLong(Unknown Source)
at org.hibernate.type.LongType.get(LongType.java:28)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:163)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:189)
tABLE DEFINITION :
CREATE TABLE "PRODUCTLIST"
(
PRICELIST_PUBLISH_KEY decimal(22) NOT NULL,
PRODUCT_NBR varchar2(54) NOT NULL,
PRODUCT_KEY decimal(22),
PRODUCT_DESCRIPTION varchar2(360),
PRODUCT_FAMILY_NBR varchar2(30),
PRODUCT_FAMILY_DESCR varchar2(180),
PRODUCT_GROUP_NBR varchar2(30),
PRODUCT_GROUP_DESCR varchar2(180),
PRODUCT_LINE_NBR varchar2(30),
PRODUCT_LINE_DESCR varchar2(180),
PRODUCT_CLASS_CODE varchar2(6),
LAST_PP_GENERATED_DATE_KEY decimal(22),
LAST_PP_GENERATED_DATE date,
PUBLISH_PERIOD_KEY decimal(22) NOT NULL,
PUBLISH_PERIOD_DATE date,
PL_KEY decimal(22),
PRODUCTLIST varchar2(750),
SALES_KEY decimal(22),
PRODUCT varchar2(60),
DM_EXTRACTED_BY_USER varchar2(90)
)
sql :
Query query = session.createSQLQuery(channelQuery)
.addScalar("PRODUCT",Hibernate.STRING)
.addScalar("PRODUCTLIST",Hibernate.STRING)
.addScalar("PRODUCTKEY",Hibernate.LONG)
.addScalar("SALESKEY",Hibernate.LONG)
.setResultTransformer(Transformers.aliasToBean(SearchResult.class));
return query.list();
}
});
Please help me to fix the issue ?
In your table definition, I can't see all the fields you're using in the addScalar() methods: there are no PRODUCTKEY nor SALESKEY fields. Instead I can see a PRODUCT_KEY and a SALES_KEY fields (underscores). I think you should use the correct name of the fields in the addScalar() methods.
But if your query is the one you put in your comments, you have to correct some details:
you should use p instead of pub as alias for the table name. As there is only one table in the query, you can suppress the alias.
In your SELECT clause, p.productprice is not an existing field in your table. Maybe you want to use p.pricelist instead.
In your WHERE clause, p.productnbr is not an existing field in your table. You should use p.product_nbr instead.
Then you should change the field names in the addScalar() methods to match those you are using in the query.
Modified query
SELECT distinct p.product, p.productlist, p.PL_KEY, p.SALES_KEY
FROM productlist p
WHERE p.product_nbr in ('1002102')
Your code should be:
Query query = session.createSQLQuery(channelQuery)
.addScalar("PRODUCT",Hibernate.STRING)
.addScalar("PRODUCTLIST",Hibernate.STRING)
.addScalar("PL_KEY",Hibernate.LONG)
.addScalar("SALES_KEY",Hibernate.LONG)
.setResultTransformer(Transformers.aliasToBean(SearchResult.class));
return query.list();
If you define aliases in your query, then you can use the alias names instead of the field names. For example, with this query:
SELECT distinct p.product, p.productlist, p.PL_KEY as PRODUCTKEY, p.SALES_KEY as SALESKEY
FROM productlist p
WHERE p.product_nbr in ('1002102')
you can use the following code (it's your original code):
Query query = session.createSQLQuery(channelQuery)
.addScalar("PRODUCT",Hibernate.STRING)
.addScalar("PRODUCTLIST",Hibernate.STRING)
.addScalar("PRODUCTKEY",Hibernate.LONG)
.addScalar("SALESKEY",Hibernate.LONG)
.setResultTransformer(Transformers.aliasToBean(SearchResult.class));
return query.list();
I'm trying to update every record for which I have the id in my arraylist but I'm getting this error:
IllegalStateException occured : org.hibernate.hql.QueryExecutionRequestException: Not supported for DML operations [update models.UserOnline uo SET currentRoom_id = :roomid where uo.id IN (:list)]
This is what I'm trying:
Query update_query = JPA.em().createQuery("update UserOnline uo SET currentRoom_id = :roomid where uo.id IN (:list)");
update_query.setParameter("roomid", null);
update_query.setParameter("list", idlist);
List<UserOnline> actual = update_query.getResultList();
Any ideas what's wrong?
I would try with update_query.executeUpdate();
From the docs.
Like Gonzalo already said, you'd have to use executeUpdate().
This is because you're actually MODIFYing data .
You only use getResultList() or getSingleResult() if you want to GET data out of the database.
a little helper:
use executeUpdate() if your query has the form
UPDATE ... SET .. WHERE ..
or
DELETE ... WHERE ...
use getResultList() or getSingleResult() if the query looks like
SELECT ... FROM xxx WHERE ...
or just
FROM xxx WHERE ...
Well, if we use Spring Repositories (CrudRepository or any of its type), and if we have a method declaration with an update Query
That is,
#Query("update employee e set e.name= :name where e.id = :id")
int updateEmployee(#Param("name") String name, #Param("id") Long id);
Then we will get the related Spring Exception org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations
Just add #Modifying annotation on the method and it will be fine.
Using Hibernate's Criteria API, I want to select the record within a table with the maximum value for a given column.
I tried to use Projections, creating an alias for max(colunName), then using it in restrictions.eq(), but it keeps telling me "invalid number".
What's the correct way to do that with Hibernate?
You can use a DetachedCriteria to express a subquery, something like this:
DetachedCriteria maxId = DetachedCriteria.forClass(Foo.class)
.setProjection( Projections.max("id") );
session.createCriteria(Foo.class)
.add( Property.forName("id").eq(maxId) )
.list();
References
Hibernate Core Reference Guide
15.8. Detached queries and subqueries
I found that using addOrder and setMaxResults together worked for me.
Criteria c = session.createCriteria(Thingy.class);
c.addOrder(Order.desc("id"));
c.setMaxResults(1);
return (Thingy)c.uniqueResult();
Using the MySQL dialect, this generates a SQL prepared statement about like this (snipping out some of the fields):
select this_.id ... from Thingy this_ order by this_.id desc limit ?
I am not sure if this solution would be effective for dialects other than MySQL.
Use
addOrder(Order.desc("id"))
and fetch just the first result :)
HQL:
from Person where person.id = (select max(id) from Person)
Untested. Your database needs to understand subselects in the where clause.
Too lazy to find out if/how such a subselect can be expressed with the criteria api. Of course, you could do two queries: First fetch the max id, then the entity with that id.
The cleaner solution would also be :
DetachedCriteria criteria = DetachedCriteria.forClass(Foo.class).setProjection(Projections.max("id"));
Foo fooObj =(Foo) criteria.getExecutableCriteria(getCurrentSession()).list().get(0);
Date maxDateFromDB = null;
Session session = (Session) entityManager.getDelegate();
//Register is and Entity and assume maxDateFromDB is a column.
//Status is another entity with Enum Applied.
//Code is the Parameter for One to One Relation between Register and Profile entity.
Criteria criteria = session.createCriteria(Register.class).setProjection(Projections.max("maxDateFromDB") )
.add(Restrictions.eq("status.id", Status.Name.APPLIED.instance().getId()));
if(code != null && code > 0) {
criteria.add(Restrictions.eq("profile.id", code));
}
List<Date> list = criteria.list();
if(!CollectionUtils.isEmpty(list)){
maxDateFromDB = list.get(0);
}
To do it entirely with Detached Criteria (because I like to construct the detached criteria without a session)
DetachedCriteria maxQuery = DetachedCriteria.forClass(Foo.class)
.setProjection( Projections.max("id") );
DetachedCriteria recordQuery = DetachedCriteria.forClass(Foo.class)
.add(Property.forName("id").eq(maxId) );
For the max() function in hibernate:
criteria.setProjection(Projections.max("e.encounterId"));
I'm trying to do an update in hibernate HQL with a subselect in a set clause like:
update UserObject set code = (select n.code from SomeUserObject n where n.id = 1000)
It isnt working, it is not supported?
Thanks
Udo
I had the same problem, discovered that you need to put bulk updates in side a transaction:
tr = session.getTransaction();
tr.begin();
updateQuery.executeUpdate();
tr.commit;
From the Hibernate documentation:
13.4. DML-style operations
...
The pseudo-syntax for UPDATE and
DELETE statements is: ( UPDATE |
DELETE ) FROM? EntityName (WHERE
where_conditions)?.
Some points to note:
In the from-clause, the FROM keyword is optional
There can only be a single entity named in the from-clause. It can,
however, be aliased. If the entity
name is aliased, then any property
references must be qualified using
that alias. If the entity name is not
aliased, then it is illegal for any
property references to be qualified.
No joins, either implicit or explicit, can be specified in a bulk
HQL query. Sub-queries can be used
in the where-clause, where the
subqueries themselves may contain
joins.
The where-clause is also optional.
While the documentation doesn't explicitly mentions a restriction about the set part, one could interpret that sub-queries are only supported in the where-clause. But...
I found an 4 years old (sigh) issue about bulk update problems (HHH-1658) and according to the reporter, the following works:
UPDATE Cat c SET c.weight = (SELECT SUM(f.amount) FROM Food f WHERE f.owner = c)
I wonder if using an alias in the from-clause would help. Looks like there is some weirdness anyway.