开发者

HQL : Getting the primary key of an object

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 pri开发者_StackOverflowmary 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


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜