views:

237

answers:

3

Hi ,

I am using HQL to save an object in the DB. It is something like this

Query query = sessionFactory.getCurrentSession().createQuery(ASK_FOR_HELP_SAVE_QUERY);
        query.setInteger("status", askForHelp.getStatus());
        query.setString("requestId", askForHelp.getRequestId());
        query.setString("toAccountId", askForHelp.getToAccountId());
        query.setDate("creationDate", askForHelp.getCreationDate());
        query.executeUpdate()

;

Now i want the primary key(sequence in DB) of the created object in the DB. I cannot use the select query because no combination of fields will make this object unique in the DB , except the primary key.

I there a way to do this.

Thanks! Pratik

A: 

The Primary Key can be anything. If you don't know what it will be, then even if Query had some method returning Object, you couldn't cast to it.

The proper way to do what you are doing is not HQL. Session / EntityManager have a a number of methods (save / persist / merge(), etc), which set your primary key (if it is generated), and you can get it from via your object's getter.

Generally speaking, use HQL only for SELECTS. Even if an update/delete query seems the same as calling delete(), HQL doesn't handle cascades, so exceptions are inevitable.

Bozho
+2  A: 

The foremost question is "why?" That is, unless you've really meant to type createSQLQuery() above.

If you're using HQL that means you already have your entity mapped. If that's the case, why not use session.save() or session.saveOrUpdate()? You can configure a generator for your entity's id and it will automatically be populated for you after the entity is saved.

For sequence you'd use something like:

<id name="id" type="long" column="my_id">
    <generator class="sequence">
            <param name="sequence">my_id_sequence</param>
    </generator>
</id>

Now, if you're actually using SQL and not HQL then you need to rethink your logic and select current value for sequence prior to save.

ChssPly76
A: 

Instead of using your query code, you should take advantage of the power of hibernate by just calling session.save() on your java objects e.g:

sessionFactory.getCurrentSession().save(askForHelp);

And then straight after that, you can do this to get the object's primary key (assuming it's called id):

askForHelp.getId();
jackocnr