1

I want to transform a simple query into hibernate

INSERT INTO TRXENTRIES (AMOUNT, BALANCE) 
VALUES (2500, (SELECT CURRENTBALANCE FROM CUSTOMER WHERE CUSTOMERID=1)+2500))

What is alternative solution in hibernate using save()?

Update Me !

Shahid Ghafoor
  • 2,991
  • 17
  • 68
  • 123
  • 1
    http://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch04.html#d0e2116 see this link this will help – ankit Aug 27 '13 at 06:26
  • 1
    http://stackoverflow.com/questions/12745041/inserting-data-in-one-table-using-hql-in-hibernate see this answer as well – ankit Aug 27 '13 at 06:31
  • @ankit is it possible with `session.save(entity)` because this is ok for one table and but In my case there are one to many relation with table so save() return the ID (Generated Value) but query does not ! – Shahid Ghafoor Aug 27 '13 at 06:43
  • @ankit I have required only one value form other table ! your example take all value from other table ! :( – Shahid Ghafoor Aug 27 '13 at 08:16

1 Answers1

0

you must:

  1. Create an entity to map your INSERT table (i.e. TrxEntry)
  2. Write an HQL query to fill your object
  3. Save entity using session.merge()

Alternatively, you can use method createSqlQuery of session object to execute your SQL query and complete them with session.executeUpdate().

Sample:

Entity TrxEntry:

public class TrxEntry {
    private Double amount;
    private Double balance;

    -- add your get / set properties

    public Trxentry (Double amount, Double balance) {
        this.amount = amount;
        this.balance = balance;
    }
}

Hql:

String hql = "select new TrxEntry(o.amount, o.balance)
from otherEntry o";

if you want calculate your o.balance as another subquery you can do without problem

The result of your query goes in

Query q = session.createQuery(hql);
session.merge(q);

Merge provides to save your entity

Joe Taras
  • 15,166
  • 7
  • 42
  • 55
  • `In HQL, only the INSERT INTO … SELECT … is supported; there is no INSERT INTO … VALUES. HQL only support insert from another table.` so sql query concept will not apply in my case, I just require only one value from other table ! – Shahid Ghafoor Aug 27 '13 at 09:36
  • I will appreciate if your provide me the example with respect to `session.merge()` or `session.save()` :) – Shahid Ghafoor Aug 27 '13 at 09:38
  • Hi, show here: http://stackoverflow.com/questions/170962/nhibernate-difference-between-session-merge-and-session-saveorupdate and http://stackoverflow.com/questions/7475363/differences-among-save-update-saveorupdate-merge-method-in-session-object – Joe Taras Aug 27 '13 at 09:58
  • Dear difference I know! I required to save entity, and this entity contain one value from another table ! – Shahid Ghafoor Aug 27 '13 at 10:05
  • @Shahid Ghafoor: Dear the solution is in point 1. As you write your entity. BALANCE is a scalar property, so if you write your HQL query you fill that property with istantiate your constructor – Joe Taras Aug 27 '13 at 10:09