Hibernate doesn´t work as expected - java

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

Related

procedure call not working from java call

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()

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 batch insert a list into a table which has unique column

I hava a list contains 1,000,000 records.
I want to insert the list into a table which already have 5,000,000 records.
The code:
Sample s = null;
for(int i=0,len=list.size();i<list;i++){
s = new Sample();
session.save(s);
if(i%20==0){
session.flush();
session.clear();
}
}
A column in this table is unique column.
Some records in this list is same to records in this table.
like this:
list : ['a','b','c']...
table : ['a','d','e']...
'a' is duplicate, so this code can't word well.
Exception: don't flush the Session after an exception occurs
It's too sloooooooooooow to use this:
String sql = 'insert ignore into xxxxx';
session.createSqlQuery().executeUpdate();
How should I do? Help me, please~~~

Obtain id of an insert in the same statement [duplicate]

This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 7 years ago.
Is there any way of insert a row in a table and get the new generated ID, in only one statement? I want to use JDBC, and the ID will be generated by a sequence or will be an autoincrement field.
Thanks for your help.
John Pollancre
using getGeneratedKeys():
resultSet = pstmt.getGeneratedKeys();
if (resultSet != null && resultSet.next()) {
lastId = resultSet.getInt(1);
}
You can use the RETURNING clause to get the value of any column you have updated or inserted into. It works with trigger (i-e: you get the values actually inserted after the execution of triggers). Consider:
SQL> CREATE TABLE a (ID NUMBER PRIMARY KEY);
Table created
SQL> CREATE SEQUENCE a_seq;
Sequence created
SQL> VARIABLE x NUMBER;
SQL> BEGIN
2 INSERT INTO a VALUES (a_seq.nextval) RETURNING ID INTO :x;
3 END;
4 /
PL/SQL procedure successfully completed
x
---------
1
SQL> /
PL/SQL procedure successfully completed
x
---------
2
Actually, I think nextval followed by currval does work. Here's a bit of code that simulates this behaviour with two threads, one that first does a nextval, then a currval, while a second thread does a nextval in between.
public void checkSequencePerSession() throws Exception {
final Object semaphore = new Object();
Runnable thread1 = new Runnable() {
public void run() {
try {
Connection con = getConnection();
Statement s = con.createStatement();
ResultSet r = s.executeQuery("SELECT SEQ_INV_BATCH_DWNLD.nextval AS val FROM DUAL ");
r.next();
System.out.println("Session1 nextval is: " + r.getLong("val"));
synchronized(semaphore){
semaphore.notify();
}
synchronized(semaphore){
semaphore.wait();
}
r = s.executeQuery("SELECT SEQ_INV_BATCH_DWNLD.currval AS val FROM DUAL ");
r.next();
System.out.println("Session1 currval is: " + r.getLong("val"));
con.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Runnable thread2 = new Runnable(){
public void run(){
try{
synchronized(semaphore){
semaphore.wait();
}
Connection con = getConnection();
Statement s = con.createStatement();
ResultSet r = s.executeQuery("SELECT SEQ_INV_BATCH_DWNLD.nextval AS val FROM DUAL ");
r.next();
System.out.println("Session2 nextval is: " + r.getLong("val"));
con.commit();
synchronized(semaphore){
semaphore.notify();
}
}catch(Exception e){
e.printStackTrace();
}
}
};
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
t1.start();
t2.start();
t1.join();
t2.join();
}
The result is as follows:
Session1 nextval is: 47
Session2 nextval is: 48
Session1 currval is: 47
I couldn't comment otherwise I would have added to Vinko Vrsalovic's post:
The id generated by a sequence can be obtained via
insert into table values (sequence.NextVal, otherval)
select sequence.CurrVal
ran in the same transaction as to get a consistent view.
Updating de sequence after getting a nextval from it is an autonomous transaction. Otherwise another session would get the same value from the sequence. So getting currval will not get the inserted id if anothers sesssion has selected from the sequence in between the insert and select.
Regards,
Rob
The value of the auto-generated ID is not known until after the INSERT is executed, because other statements could be executing concurrently and the RDBMS gets to decide how to schedule which one goes first.
Any function you call in an expression in the INSERT statement would have to be evaluated before the new row is inserted, and therefore it can't know what ID value is generated.
I can think of two options that are close to what you're asking:
Write a trigger that runs AFTER INSERT, so you have access to the generated ID key value.
Write a procedure to wrap the insert, so you can execute other code in the procedure and query the last generated ID.
However, I suspect what you're really asking is whether you can query for the last generated ID value by your current session even if other sessions are also inserting rows and generating their own ID values. You can be assured that every RDBMS that offers an auto-increment facility offers a way to query this value, and it tells you the last ID generated in your current session scope. This is not affected by inserts done in other sessions.
The id generated by a sequence can be obtained via
insert into table values (sequence.NextVal, otherval)
select sequence.CurrVal
ran in the same transaction as to get a consistent view.
I think you'll find this helpful:
I have a table with a
auto-incrementing id. From time to
time I want to insert rows to this
table, but want to be able to know
what the pk of the newly inserted row
is.
String query = "BEGIN INSERT INTO movement (doc_number) VALUES ('abc') RETURNING id INTO ?; END;";
OracleCallableStatement cs = (OracleCallableStatement) conn.prepareCall(query);
cs.registerOutParameter(1, OracleTypes.NUMBER );
cs.execute();
System.out.println(cs.getInt(1));
Source: Thread: Oracle / JDBC Error when Returning values from an Insert
I couldn't comment, otherwise I would have just added to dfa's post, but the following is an example of this functionality with straight JDBC.
http://www.ibm.com/developerworks/java/library/j-jdbcnew/
However, if you are using something such as Spring, they will mask a lot of the gory details for you. If that can be of any assistance, just good Spring Chapter 11, which is the JDBC details. Using it has saved me a lot of headaches.

Categories