0

I want to check existance of object in database without knowing his id. I'm using a HQL query for it, but i'm recieving an excenption

org.hibernate.TransientObjectException: 
object references an unsaved transient instance - save the transient instance before flushing

Here is my code exapmle:

ObjectToCheck obj = new ObjectToCheck(); //this is a mapped entity
obj.setName("name");
obj.setValue("value");
List list = session.createQuery("from ObjectToCheck as o where o = ?")
        .setEntity(0, obj)
        .list();

I understand the reason of this exception, but how can i make query with transistent object as a parameter? I want to know, is the equal object in database or not.

1
  • Does your object have an id attribute? Commented Feb 1, 2012 at 9:38

2 Answers 2

4

I don't think the exception comes from the fact that you're using a transient entity as a parameter of your query (although this query is also wrong, see below).

The exception comes from the fact that Hibernate flushes the session before executing the query, but you have attached a transient entity to an attached one in the session. It thus tries to save the association, but since the object is transient and doesn't have any ID yet, this is not possible.

Now your query: where o = ? won't magically query by name and value. It will query by ID. And this is precisely what you don't want to do. The query should thus be:

select o from ObjectToCheck o where o.name = :name and o.value = :value

And you should bind both parameters. Another way to do this is to use a query by example. See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#querycriteria-examples.

Sign up to request clarification or add additional context in comments.

1 Comment

I've posted too simple example. I have the set of related objects by many to one besides the name and value(like in the yeasterday's question). I'm still trying to make it without loops:(
0

Another (and better) option is:

from ObjectToCheck as o where o.name = :#{#obj.name}

This solution has already been suggested in another post.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.