views:

34

answers:

1

Hi, new to hibernate. I have a problem that when i am trying to run select query say

"from Foo where Foo.some_id=2"

(with hibernate template) then hibernate is also tries to insert the records in a table 'Foo2' that has a one-2-one association with the Foo table

Bean Foo

class Foo{
int id;
....
Foo2 foo2;
}

Foo.hbm.xml

...
<one-to-one name="foo2" class="Foo2" property-ref="foo"
  constrained="false" cascade="save-update"></one-to-one>
...

Bean Foo2

Class Foo2{
...
private int foo;
...
}

Foo2.hbm.xml

...
<property name="foo" column="foo_id"/>
...

Usage

 DetachedCriteria criteria = createDetachedCriteria();
  criteria.add(Restrictions.eq("some_id", value));
  return getHibernateTemplate().findByCriteria(criteria);

urgent help would be appreciated :) thx

    public List<SnsUser> getAllSnsUsersByProperty(String prop, Object val){
            String query = "from SnsUser su where su." + prop + " =:" + prop;
            return executeQuery(query, new String[]{prop}, new Object[]{val});
    }

    public static void main(String[] args) { //WORKING
    String query = "from SnsUser su where su.blessUserId=1";
    Session session = Utility.getSessionFactory().openSession();
    List l = new SnsUserDaoImpl().getQRes(query);
    System.out.println(l);
    session.close();
    }
public List<E> executeQuery(String queryString, String []param, Object [] val){
//NOT WORKING
        return getHibernateTemplate().findByNamedParam(queryString, param, val);
    }   

This is what i am getting...

Hibernate: select * from bless_aggregation.sns_user this_ left outer join bless_aggregation.sns_authenticator snsauthent2_ on this_.sns_uid=snsauthent2_.sns_uid 
where this_.bless_uid=?
Hibernate: select * from bless_aggregation.bless_user blessuser0_ where blessuser0_.bless_uid=?
Hibernate: select * from bless_aggregation.sns_user snsuser0_ left outer join bless_aggregation.sns_authenticator snsauthent1_ on 
snsuser0_.sns_uid=snsauthent1_.sns_uid where snsuser0_.bless_uid=?

Hibernate: insert into bless_aggregation.sns_authenticator (key, value, sns_uid) values (?, ?, ?)
1079 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1064, SQLState: 42000
1079 [main] ERROR org.hibernate.util.JDBCExceptionReporter - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, value, sns_uid) values (null, null, 1)' at line 1
A: 

My guess is that you have pending changes in the session (some Foo2 instances waiting to be inserted) and, by default, Hibernate flushes the session before running a query to give you non stale results. This is explained in the following section of the documentation:

10.10. Flushing the Session

Sometimes the Session will execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in memory. This process, called flush, occurs by default at the following points:

  • before some query executions
  • from org.hibernate.Transaction.commit()
  • from Session.flush()

The SQL statements are issued in the following order:

  1. all entity insertions in the same order the corresponding objects were saved using Session.save()
  2. all entity updates
  3. all collection deletions
  4. all collection element deletions, updates and insertions
  5. all collection insertions
  6. all entity deletions in the same order the corresponding objects were deleted using Session.delete()

An exception is that objects using native ID generation are inserted when they are saved.

Except when you explicitly flush(), there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed. However, Hibernate does guarantee that the Query.list(..) will never return stale or incorrect data.

It is possible to change the default behavior so that flush occurs less frequently. The FlushMode class defines three different modes: only flush at commit time when the Hibernate Transaction API is used, flush automatically using the explained routine, or never flush unless flush() is called explicitly. The last mode is useful for long running units of work, where a Session is kept open and disconnected for a long time (see Section 11.3.2, “Extended session and automatic versioning”).

sess = sf.openSession();
Transaction tx = sess.beginTransaction();
sess.setFlushMode(FlushMode.COMMIT);

// allow queries to return stale state

Cat izi = (Cat) sess.load(Cat.class, id);
izi.setName(iznizi);

// might return stale data
sess.find("from Cat as cat left outer join cat.kittens kitten");

// change to izi is not flushed!
...
tx.commit(); // flush occurs
sess.close();

During flush, an exception might occur (e.g. if a DML operation violates a constraint). Since handling exceptions involves some understanding of Hibernate's transactional behavior, we discuss it in Chapter 11, Transactions and Concurrency.

So, as explained above and as shown in the code snippet, try to use FlushMode.COMMIT.

Note that this won't help if you are using an identity generator, Hibernate will write to the database at save time.

Also note that the FlushMode is just an hint for the Session, the behavior is not strictly guaranteed.

Pascal Thivent
@user330281 You're welcome. Does it make sense in your context?
Pascal Thivent
thank you for replying. but there is no point of inserting the records. am just using the hibernate template method (findByNamedParam(...)) and dont want to insert. and when i execute it without template it works fine.
sorry could not post whole of the message.
@user330281 I'm just trying to guess what could be happening from details you didn't provide :) I might be wrong, especially if you don't get the same behavior when using Spring or not. Could you post some pseudo code to illustrate things that work (and how you interact with the session)?
Pascal Thivent
yes. am using Spring to initialize session.
i have added code snippets, one is workin i.e. just selects the records and gets end. and other (template 1) tries to insert as well.