I saw a tutorial in the web showing you can do something like this for deletes and updates in Hibernate:
Query query = session.createQuery("delete Stock where stockCode = :stockCode");
query.setParameter("stockCode", "7277");
int result = query.executeUpdate();
In the same tutorial I came across this code for insertion:
Query query = session.createQuery("insert into Stock(stock_code, stock_name)" +
"select stock_code, stock_name from backup_stock");
int result = query.executeUpdate();
My question is, is it possible to do something like the delete example from the tutorial, but for the insertion method instead, by using setParameter? I tried something like this and got an error:
Query q = session.createQuery("insert into test(:testname)");
q.setParameter("testname", "tester");
The error was regarding properties. One of my reason to use the above code is because of the
int result = query.executeUpdate()
which can return a result to verify whether I successfully inserted via the SQL command or not.
First thing :
has been create for parameters in HQL queries, not field name.
Second thing :
Your request :
insert into test(:testname)seems incomplete, it should be something likeinsert into [TABLE_NAME]([FIELD_NAME],...) values ([VALUE],...)and In that case you should use SQL queries with :See: http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#createSQLQuery(java.lang.String)
. Why do you need to make your query so dynamic ?
And an insert into the database would be better with a save :
with youHibernateObject an object mapped with hibernate model mapping schemas. Good luck.