I have an entity class:
Cabbage.java
package womble;
public class Cabbage {
private int id;
// getters, setters, etc.
}
That I've got mapped to two separate database tables as follows:
Cabbage.hbm.xml
<hibernate-mapping>
<class name="womble.Cabbage"> <!-- Using the default entity and table name. -->
<id name="id" unsaved-value="null">
<generator class="native"/>
</id>
</class>
</hibernate-mapping>
CabbageBackup.hbm.xml
<hibernate-mapping>
<class name="womble.Cabbage" entity-name="CabbageBackup" table="cabbage_backup">
<id name="id">
<generator class="assigned"/>
</id>
</class>
</hibernate-mapping>
I'm trying to retrieve the last saved Cabbage instance like this:
CabbageDao.java
package womble;
public class CabbageDao {
Session session; // Hibernate session
String GET_MAX_ID = "select max(id) from Cabbage";
public getLastCabbage() {
Object lastId = session.createQuery(GET_MAX_ID).uniqueResult();
return session.load(Cabbage.class, lastId);
}
}
This blows up with a NonUniqueResultException
: "query did not return a unique result: 2"
Looking through the logs, Hibernate apparently queries both the tables and then joins the results together.
Is there a way to make Hibernate only query the default mapping for an entity? (That is, to specifically prevent it from magically querying both mappings when I use the simple class name.)
I tried using the above, using the criteria API passing Cabbage.class to #createCriteria(), as well as the string "Cabbage", both select from both tables. I'm trying to avoid specifying an entity name to the "main" mapping, because there's multiple classes like that in my code and I'd have to fix up all the relationships between them as well.