Pazonec
Pazonec

Reputation: 1559

Hibernate. HQL query with transistent object as a parameter

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.

Upvotes: 0

Views: 2964

Answers (2)

Rafael Pizao
Rafael Pizao

Reputation: 841

Another (and better) option is:

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

This solution has already been suggested in another post.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692231

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.

Upvotes: 4

Related Questions