views:

32

answers:

1

I am attempting to create an object in hibernate using a query, which will then be saved back to the table representing the class.

Excerpt from hbm.xml file:

<class name="MyClass" table="MY_TABLE">
<id column="ID" name="ID">
   <generator class="sequence">
    <param name="sequence">MY_SEQ</param>
   </generator>
</id>
  <property column="VAL" name="val" type="string"/>
</class>

<sql-query name="myQuery">
  <return class="MyClass"/>
  SELECT MY_SEQ.nextval ID, 'something' VAL from DUAL
</sql-query>

Code snippet from test case:

MyClass myClass = (MyClass) session.getNamedQuery("myQuery").list().get(0);
Transaction t = session.beginTransaction();
session.save(myClass);
t.commit();

My aim is that there should now be a new record in table MY_TABLE, but the insert does not occur, I assume that this is due the fact that Hibernate does not know that the instance has not been persisted in the db.

I have tried changing the query to read:

SELECT NULL ID, 'something' VAL from DUAL

But this results in Hibernate not instantiating an object.

So how can i create a new object instance from a query that is not associated with a persisted instance of the class and use this to create a persisted instance?

+1  A: 
Pascal Thivent
Pascal, the system that i am working on is generating financial transactions based upon services rendered. So what i am doing is scanning the DB for transactions that need to be generated. My plan was that the select would identify and in effect create the required transaction objects, which would then be processed (complex operations) and then stored as appropriate to the DB. In effect I am trying to get hibernate to create the transient objects for me and then later persist them as necessary. A secondary objective is to keep all the SQL statement config in the mapping file.
stjohnroe
@stjohnroe: OK, I see. I did some testing and couldn't get the initial suggestion to work as I wanted. But I've updated my answer with an alternative approach which seems to work.
Pascal Thivent