procedure call not working from java call - java

I have created a procedure which updates a table row in DB and returns a specific string(e.g 'done') after the update it returns a different response if the value is not updated(e.g 'fail').
When calling from MySQL tool it's updating the table and returning the value in response
call LoginCheck('9111111114','AGGR001002','11d3ad9315b7be5dd53b31a273b3b3aba5defe700808305aa16a3062b76658a791','DIST001007');
However when I am calling the same procedure from Java code it's returning the proper response i.e 'done', but when I am checking the table it seems that it has not updated the respective table row.
factory = DBUtil.getSessionFactory();
Session session = factory.openSession();
Transaction transaction = session.beginTransaction();
String status = "7000";
List objectList = null;
SQLQuery query = session.createSQLQuery("call LoginCheck(:userid,:AggId,:Password,:id)");
query.setString("userid", userid);
query.setString("AggId", AggId);
query.setString("Password", Password);
query.setString("id", id);
objectList = query.list();
I have already tried query.setParameter and query.ExecuteUpdate()
Please let me know if anything else is required from my side.

It seems that you have begin your transaction but not committed it . so try commit it .
Transaction transaction = session.beginTransaction();
transaction.commit()

Related

Hibernate doesn´t work as expected

I am trying to update MySQL table with hibernate. It looks like that it does work, result from hibernate is 1, but table doesn´t change. My code for update :
Session session = GeneralSession.getSession();
session.beginTransaction();
//some code - initialization and logics
//loop
Query updateDuplicity = session .createSQLQuery("UPDATE `t_inzerat` set `actual` = 'D'
WHERE `id` = "+ idSimi);
int resultUpdate = updateDuplicity.executeUpdate();
session.flush();
//end of loop
session.getTransaction().commit();
In console hibernate writes this as:
Hibernate: UPDATE `t_inzerat` set `actual` = 'D' WHERE `id` = 5611
Affected rows : 1
Please what is wrong? Thank you
Have a look hereexample. Do the commit in the tx returned by beginTransaction method

What I am missing here (Hibernate begin transaction)

I have a test class :
class SomeTest {
public static void main(String args[]){
Client kom = new Client();
kom.setId(kom.newID());
kom.setClient("OldName");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(kom); // I think insert is here ?
Query q = session.createSQLQuery(" call change_name(:old, :new) ");
q.setParameter("old","OldName");
q.setParameter("new","NewName");
int result = q.executeUpdate();
session.getTransaction().commit();
}
};
And database stored procedure change_name which do update of name of client.. every time I run test I have one record with old name ?? I expect that update is execute in same transaction and that I never see old name ?
JB Nizet has right answer..
save() does NOT insert. It associates the object with the session. The insert query is executed at the next flush. So call flush explicitely before calling your stored proc. – JB Nizet yesterday
There is also FlushMode ... I set to ALWAYS. I call many procedures which change data in database..

How can I add a value to a column?

I want to add a value to an existing column, but I don't want to have to select it first. Right now I would have to do something like
// run hql in a named query
from Employee where id = :id
// after running the above
e.setBonus(e.getBonus() + 100); // add 100 to e's bonus
// commit to database
HibernateUtil.saveOrUpdate(e);
But I want something that's just one-and-done - something like
update Employee e set e.bonus = e.bonus + 100
Is this something I can do in Hibernate? If so, how. If not, what's the suggested best practice for such an update?
You could create a hql query that just does an update
Query updateBonus = createQuery("UPDATE Employee SET bonus = bonus+100 WHERE id = :id" );
updateBonus.setInteger("id", employee.getId());
updateBonus.executeUpdate();
Yes, you can do it as intended with hql query. Try such code:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hql="update Employee e set e.bonus = e.bonus + :p where id=:id";
session.createQuery(hql).setInteger("p",100).setInteger("id",id).executeUpdate();
tx.commit();
session.close();
More info you can find by the link

Hibernate Iterator retrieving same data

I have a form that is connected to the database via hibernate. With this form, the user can go in and fill out fields such as names, address, and email information, etc. After they are all done filling out information they would submit the form. After submit, all the information would be display on a data table on the same page.
I am using session to interact with the database. However, the data that is being populated from database doesn't seem to be right.
public void somefunction() {
//The sessionfactory is being configured in another class
Session s = sessionFactory.openSession();
Transaction tx= null;
try {
tx= s.beginTransaction();
List userInformation = s.createQuery("FROM database1 WHERE PKEY ='"+somevalue+"'").list();
for(Iterator iterator = userInformation.iterator; iterator.hasNext();){
//database1 is an entity bean
database1 x = (database1) iterator.next();
System.out.print(x.getName());
}
tx.commit();
}
catch(Exception) {......}
finally {.....}
}
After the user submit the first "user" with their information, everything shows up in the datatable fine. However, when they enter a second "user" the row displayed on the datatable is the same information as the first user, even though the data is different. I think the code looks correct, so i am not sure what could be wrong with this.
you should use primary key to get correct value.
List userInformation = s.createQuery("FROM database1 where yourId='PK'").list();
In your query always it will return first row.
Found the solution.
Instead of using session.createQuery("QUERY"), I used
Criteria cr = session.createCriteria(SomeClass.class)
cr.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
cr.add(/* add some filters here */);
ScrollableResults sr = cr.scroll(ScrollMode.FORWARD_ONLY);
while(sr.next) {
someObject so = (someObject) sr.get(0);
//Do action here
}
that solved my problem of returing a single result.

hibernate java select queries

i am new to this and today i tried to play hibernate with a method that returns the result of selected row...if is selected then it can return the result in int.. here is my method
public int validateSub(String slave, String source, String table){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query q = session.createQuery("from Subscribers where slave = :slave AND source = :source AND tbl = :tbl");
q.setParameter("slave", slave);
q.setParameter("source", source);
q.setParameter("tbl", table);
int result = q.executeUpdate();
return result;
}
from this method i tried to validate the 3 values that i get from the Subscribers table but at the end i tried to compile having this error
Exception in thread "Thread-0" org.hibernate.hql.QueryExecutionRequestException: Not supported for select queries [from com.datadistributor.main.Subscribers where slave = :slave AND source = :source AND tbl = :tbl]
You can have a look at the below links that how executeUpdate works, one is from the hibernate docs and other the java docs for JPA which defines when the exception is thrown by the method
http://docs.oracle.com/javaee/6/api/javax/persistence/Query.html#executeUpdate()
https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#executeUpdate()
Alternatively you can use
List list = query.list();
int count = list != null ? list.size() : 0;
return count;
you are running a select query, Eventhough you are not using the select keyword here hibernate will add that as part of the generated SQL.
what you need to do to avoid the exception is the say
q.list();
now, this will return a List (here is the documentation).
if you are trying to get the size of the elements you can say
Query q = session.createQuery("select count(s) from Subscribers s where slave = :slave AND source = :source AND tbl = :tbl");
Long countOfRecords = (Long)q.list().get(0);
you can execute update statements as well in HQL, it follows a similar structure as SQL (except with object and properties).
Hope this helps.
here you want to select record so it is posible without select key word
sessionFactory sesionfatory;
ArrayList list = (ArrayList)sessionfactory.getCurruntSession().find(from table where name LIKE "xyz");
long size = list.get(0);
I also happened to make the same mistake today.
Your SQL statement is not correct.
You can try:
DELETE from Subscribers WHERE slave = :slave AND source
Try this:
int result = q.list().size();

Categories