Java – Get Hibernate Entity instance from id column in SQLQuery result

hibernatejavasql

I have (non-Hibernated) database tables that contain ids for Hibernate entities. I can query them (using createSQLQuery), which gives me the ids, from which I can then load the entities.

I'd like to do that in one step, and I think I can do that with addEntity, but I am not sure how exactly. (Hibernate's documentation web site is down. Again.) I can use addEntity when all the columns for the entity table are present, but I have only the id now.

This complains about the missing columns:

return (List<MyEntity>) session.createSQLQuery(
            "select entity_id from the_table where foreign_key_value = ?")
            .addEntity("entity_id", MyEntity.class)
            .setLong(0, foreignKey).list();

Best Solution

I think you want something like:

session.createSQLQuery("select {entity.*} from entity_table {entity} where ....")
  .addEntity("entity", Entity.class).(bind-parameters).list();

Hibernate will expand "{entity.*}" to be the relevant columns from entity_table.

Although if you already have the IDs, you can simply use session.load() to convert those to actual instances (well, lazy-load proxies).