Hibernate eager loading (fetch all properties does not work) - java

Basically I want to eager-load properties. I have the following HQL query:
SELECT u.id AS id, u.name AS text, u AS obj FROM User AS u fetch all properties
I would expect this to execute one query only. Instead I got N+1 queries.
The code is the following:
Query q = mySession.createQuery(
"SELECT u.id AS id, u.name AS text, u AS obj FROM User AS u fetch all properties")
.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
for (Iterator i = q.iterate(); i.hasNext();) {
Object line = i.next();
System.out.println(line);
}
The output I get (with hibernate.show_sql set to true) is:
Hibernate: select user0_.id as col_0_0_, user0_.name as col_1_0_, user0_.id as col_2_0_ from user user0_
Hibernate: select user0_.id as id0_0_, user0_.name as name0_0_, user0_.location as location0_0_ from user user0_ where user0_.id=?
{id=1, obj=User#b6548 [id='1' name='John' ], text=John}
Hibernate: select user0_.id as id0_0_, user0_.name as name0_0_, user0_.location as location0_0_ from user user0_ where user0_.id=?
{id=2, obj=User#4865ce [id='2' name='Arnold' ], text=Arnold}
Ps: The situation is just the same without transformers.
Edit:
The file with the entity-mappings:
<hibernate-mapping>
<class name="User" table="user">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name"/>
<property name="location"/>
<map name="customPrices" table="custprice">
<key column="user"/>
<map-key-many-to-many column="product" class="Product"/>
<element column="price" type="double"/>
</map>
</class>
<class name="Product" table="product">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name"/>
<property name="listprice"/>
</class>
</hibernate-mapping>
I tried adding lazy="false" to the class and to the individual properties. No difference.
My configuration file:
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://192.168.0.203/hibtest</property>
<property name="connection.username">hibtest</property>
<property name="connection.password">hibb345</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="combined.hbm.xml" />
</session-factory>
</hibernate-configuration>
Edit2:
Even the following code causes N+1 query. Although I only fetch the ID field, which according to documentation should not cause objects to load.
for (Iterator i = q.iterate(); i.hasNext();) {
Object line = i.next();
User u = (User)((Map)line).get("obj");
System.out.println(u.getId());
}

The problem was with .iterate(). According to Hibernate API docs:
Entities returned as results are initialized on demand. The first SQL query returns identifiers only.
This is a special function to be used when we expect the resulting objects to be already cached. They will be (lazy) loaded when accessed.
So for general use, to get an iterator on a result of a query you should use .list().iterate().
Thanks for Eran Harel for the help.

In essense, the cause of your problem is an attempt to incorporate result transformation logic into a query.
I think it would be better to make a simple HQL query and then apply your specific result transformation logic in a custom ResultTransformer, something like this:
Query q = mySession.createQuery("FROM User")
.setResultTransformer(new ResultTransformer() {
public List transformList(List l) { return l; }
public Object transformTuple(Object[] tuple, String[] aliases) {
Map<String, Object> r = new HashMap<String, Object>();
User u = (User) tuple[0];
r.put("obj", u);
r.put("id", u.getId());
r.put("text", u.getName());
return r;
}
});

Looks like it cannot retrieve the obj in a single query with separate columns.
Since you use the same values from User for the other columns, the example from #axtavt seems your best solution.

Related

Beginner hibernate: Why does my hibernate query return only one result, instead of a list?

I'm very new to hibernate, and I'm trying to set up a new method in our PersonDAO.
My hibernate mapping file looks like this:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.foo.bar.domain">
<class name="Person" table="person">
<meta attribute="class-description">A Person</meta>
<id name="id" type="java.lang.Long" column="rid" unsaved-value="null">
<generator class="native" />
</id>
<version name="version" type="integer" column="rversion" unsaved-value="null" />
<property name="UID" type="string" column="UID" length="16" not-null="true" unique="true"/>
<property name="lastName" type="string" column="last_name" not-null="true" />
<property name="firstName" type="string" column="first_name" not-null="true" />
<property name="ownDepartment" type="string" column="own_department"/>
<!-- a person has many responsibilities and a responsibility can can assigned to many person -->
<set name="responsibilities" table="person_responsibility">
<key column="person_id"/>
<many-to-many column="responsibility_id" class="Responsibility"/>
</set>
<set name="additionalDepartments" table="PERSON_TO_ADDL_DEPARTMENT">
<key column="person_id"/>
<element column="ADDITIONAL_DEPARTMENT" type="string"/>
</set>
</class>
and I've written a method like this, in java, to fetch all the managers from a given department:
public List<Person> getManagerByDepartment(final String givenDepartment){
List<Person> l = (List<Person>) this.getHibernateTemplate().executeFind(new HibernateCallback<List<Person>>() {
public List<Person> doInHibernate(Session session) throws HibernateException, SQLException {
String query = "select p from Person p join p.responsibilities responsibilities join p.additionalDepartments additionalDepartments where responsibilities.name = 'manager' and (p.ownDepartment = :givenDepartment or additionalDepartments = :givenDepartment)";
List<Person> result = (List<Person>) session.createQuery(query).setString("givenDepartment", givenDepartment).list();
return result;
}
});
return l;
}
now I do a manual query in SQL, and I can see that for a given department, there are definitely more than one people who have the additional responsibility 'manager'...why does my method only ever return one person, instead of all of them?
I have a strong suspicion that my method, specifically my query, and not the mapping, is the issue, but I can't see what's wrong with it...
I've jumped in at the deep end here, so any help would be very much appreciated.
edit: note, I'm working on hundreds of records, not millions, and this isn't exactly a bottle-neck operation, so I'm not too worried about performance...that said if I'm doing something that's pointlessly wasteful, do point it out
You can print hibernate query by enabling showsql option and check the query getting created and then test it against the database.
Hard to be sure without the sample data, but when you do join in HQL, it is translated to inner join in SQL. So, if you know that there should be more than one result with given responsibility then the problem is probably join p.additionalDepartments.
Try this query with left join for additionalDepartments and see if it works
String query = "select p from Person p join p.responsibilities responsibilities left join p.additionalDepartments additionalDepartments where responsibilities.name = 'manager' and (p.ownDepartment = :givenDepartment or additionalDepartments = :givenDepartment)";

hibernate: left outer join with Criteria API, is possible?

I'm new on Hibernate so excuse me for banality but I can't find any answer related to my problem (i tried to search on docs & on SO).
If possible, I would create a left outer join from two tables (t0 and t1) without using HQL; in my case I'd like to use only the Criteria API.
t0 { id, fieldA, fieldB }
t1 { id, fieldC, fieldD }
I don't know which fields will be used for the join, the user can decide it.
I see that the Criteria API has some nice functions such as createAlias or createCriteria but if I use these methods, I can't run a join.
Every table has a class (mapped with a specific hbm.xml) like this:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field">
<class name="it.class.T0" table="t0">
<meta attribute="class-description">Table 0</meta>
<!-- Unique id -->
<id name="id" type="long" column="id">
<generator class="native"/>
</id>
<!-- Natural key -->
<natural-id mutable="true">
<property name="fieldA" type="string" column="fieldA" not-null="true" />
<property name="fieldB" type="string" column="fieldB" not-null="true" />
</natural-id>
<!-- Fields -->
<property name="column1" type="long" column="columnd1" not-null="true" />
<property name="column2" type="string" column="column2" not-null="false" />
</class>
</hibernate-mapping>
The entity class is like this:
public class T0 implements Serializable
{
private static final long serialVersionUID = -8123118569358735984L;
public long id;
public String fieldA;
public String fieldB;
public long column1;
public String column2;
public T0()
{
super();
}
}
Is it possible to create a left outer join programmatically (with the Criteria API) without specifying in the hbm.xml (or in a specific HQL) which fields to use?
No. You can't use a hibernate api to create a join based on a mapping hibernate doesn't know anything about. It kind of defeats the purpose of using hibernate in the first place. Why not just write sql then? ;-)

Hibernate runs all tables doing a simple login

I have done some maintenances in a web system, this system was done in Java, Struts2 and Hibernate 3. One of the items that my customer asked me urgently was to correct the Login, because it's very slow.
I could identify when the user does the login, the Hibernate generates many queries on the database in different tables which does not have relation with login.
My relationship are three tables: User, Student, Teacher
Student
ID
Name
Teacher
ID
Name
User
ID
Login
Password
Every time that a student does a login the query check if it's the correct Login and Password and if the ID exists in a Student table. As you can see there is no foreign key ID, as for example, ID_USER in a Student table.
My Query:
Student student =(Student)session.createCriteria(Student.class)
.add( Property.forName("login").eq(login) )
.add( Property.forName("password").eq(password) )
.setMaxResults(1)
.uniqueResult();
Student inherits from User...
My User.hbm.xml
...
<class name="com.xxx.User" table="TBL_USERS" discriminator-value="0" lazy="true">
<id name="id" column="ID">
<generator class="sequence">
<param name="sequence">seq_users</param>
</generator>
</id>
<discriminator column="TYPE" insert="true" />
<subclass name="com.xxx.Student" discriminator-value="1" lazy="true">
<join table="TBL_STUDENTS">
<key column="ID"/>
<property name="name" column="NAME"/>
</join>
</subclass>
<subclass name="com.xxx.Teacher" discriminator-value="2" lazy="true">
<join table="TBL_TEACHERS">
<key column="ID" />
<property name="name" column="NAME" />
</join>
</subclass>
...
In my Hibernate log many strange queries, like bellow:
It's happening in more than 20 different tables and repeating all the times, because that, the login action is slow. But I don't know why it's happening, I don't have much experience with Hibernate.
Hibernate:
select
exerc0_.ID_CLASS as ID6_1_,
exerc0_.ID as ID1_,
exerc0_.ID as ID14_0_,
exerc0_.DATE_ENT as DATA2_14_0_,
exerc0_.TITLE as TITTLE14_0_,
exerc0_.TEXT as TEXT14_0_,
exerc0_.TYPE_EXERC as TYPE5_14_0_,
exerc0_.ID_CLASS as ID6_14_0_
from
TBL_EXERC exerc0_
where
exerc0_.ID_CLASS=?
What could be happening?
Just to not leave this question open forever.
The problem was fixed many time ago, but I forgot completely to reply.
I had to enable few lazy-loadings and make sure to choose LIST instead SET in few other places. Seemed more performatic with LIST.
#Firo was right in somehow.

Hibernate 'join' fetching weird behaviour

I have a user and a message table. User to Message are one-to-many relationships and Message to User are many-to-one relationships. I've marked one of the many-to-one as fetch join. When I 'get' a single Message, Hibernate runs a join query, but when I fetch all the messages, Hibernate runs select queries instead of a join. What could be the reason? Following are the details:
Relationship between them:
User
<set name="messagesForFromUserUid" lazy="true" table="message" inverse="true" cascade="save-update">
<key>
<column name="from_user_uid" not-null="true" />
</key>
<one-to-many class="repository.Message" />
</set>
<set name="messagesForToUserUid" lazy="true" table="message" fetch="select">
<key>
<column name="to_user_uid" not-null="true" />
</key>
<one-to-many class="repository.Message" />
</set>
Message
<many-to-one name="userByFromUserUid" class="repository.User" fetch="join" lazy="false">
<column name="from_user_uid" not-null="true" />
</many-to-one>
<many-to-one name="userByToUserUid" class="repository.User" fetch="select" lazy="proxy">
<column name="to_user_uid" not-null="true" />
</many-to-one>
When I fetch a single message object, Hibernate runs one join query as expected:
Message m = (Message) s.get(Message.class, 2);
Hibernate:
select
message0_.message_uid as message1_1_1_,
message0_.from_user_uid as from2_1_1_,
message0_.to_user_uid as to3_1_1_,
message0_.message_text as message4_1_1_,
message0_.created_dt as created5_1_1_,
user1_.user_uid as user1_0_0_,
user1_.user_name as user2_0_0_,
user1_.user_password as user3_0_0_,
user1_.email as email0_0_,
user1_.first_name as first5_0_0_,
user1_.last_name as last6_0_0_,
user1_.created_dt as created7_0_0_
from
hello.message message0_
inner join
hello.user user1_
on message0_.from_user_uid=user1_.user_uid
where
message0_.message_uid=?
But when I fetch all the messages in one go, Hibernate runs select queries instead:
List<Message> l = s.createQuery("from Message").list();
Hibernate:
select
message0_.message_uid as message1_1_,
message0_.from_user_uid as from2_1_,
message0_.to_user_uid as to3_1_,
message0_.message_text as message4_1_,
message0_.created_dt as created5_1_
from
hello.message message0_
Hibernate:
select
user0_.user_uid as user1_0_0_,
user0_.user_name as user2_0_0_,
user0_.user_password as user3_0_0_,
user0_.email as email0_0_,
user0_.first_name as first5_0_0_,
user0_.last_name as last6_0_0_,
user0_.created_dt as created7_0_0_
from
hello.user user0_
where
user0_.user_uid=?
Hibernate:
select
user0_.user_uid as user1_0_0_,
user0_.user_name as user2_0_0_,
user0_.user_password as user3_0_0_,
user0_.email as email0_0_,
user0_.first_name as first5_0_0_,
user0_.last_name as last6_0_0_,
user0_.created_dt as created7_0_0_
from
hello.user user0_
where
user0_.user_uid=?
Looks like Hibernate does not always use fetch strategies defined in the mapping, for HQL or Criteria queries. They are typically used for get/load. Found a reference here: https://forum.hibernate.org/viewtopic.php?f=1&t=957561
I am not sure but this might be the reason. If you run single query which is join or subquery. It is ok, there may not be any performance difference for single query. But if you are running multiple queries(in your case multiple messages), There may raise Performance issue. I would definitely choose simple select queries instead of join/subqueries. This definitely makes sense if we consider performance. This is what Hibernate does.

How to add collections to a data transfer class in Hibernate

I have the following setup where a class contains a collection. When querying instances of this class I like to populate a data transfer class rather than the data class. However, Hibernate generates a wrong SQL query. What am I missing?
The Hibernate mapping:
<class name="Thread" table="tbl_threads" schema="dbo">
<id name="Id" type="integer">
<column name="i_id"/>
<generator class="identity"/>
</id>
<set name="keywords" inverse="true" lazy="false" cascade="all-delete-orphan" optimistic-lock="false">
<key>
<column name="thread_id" not-null="true"/>
</key>
<one-to-many class="Comment"/>
</set>
<!-- ... -->
</class>
and
<class name="ThreadKeyword" table="tbl_keywords" schema="dbo">
<composite-id name="id"
class="se.ericsson.eab.sdk.fido.server.api.pojos.report.ReportThreadKeywordId">
<key-property name="keywordId" type="integer">
<column name="keyword_id" />
</key-property>
<key-property name="threadId" type="integer">
<column name="thread_id" />
</key-property>
</composite-id>
<!-- ... -->
</class>
The HQL I am using is
SELECT new Composite(t.id, t.keywords, ...)
FROM Thread t, ThreadKeyword tk
WHERE t.id = tk.id.threadId
This generates a SQL where the SELECT part contains only a dot for the keyword attribute:
select thread1_.report_id as col_0_0_, . as col_92_0_
from dbo.tbl_thread reportthre0_ inner join
dbo.tbl_keywords keywords4_ on reportthre0_.i_id=keywords4_.thread_id
It works fine when I query for the data class directly, i.e.
SELECT t
FROM Thread t, ThreadKeyword tk
WHERE t.id = tk.id.threadId
As I understand will Hibernate not find a column name for keywords in the thread table. That is right, since it is a collection. It rather needs to be populated using subsequent queries. If I omit the keywords in the constructor for the Composite class the query gets right but Hibernate won't populate the Set.
How do I get the keywords set populated?
You cannot do that with a collection.
t.id is a column/value
so Hibernate translates that into thread1_.report_id as col_0_0_. Hibernate even gave it the alias col_0_0_
t.keywords is a set of values so Hibernate just can't translate the collection into a column/value.
A query includes a list of columns to be included in the final result
immediately following the SELECT keyword - Wikipedia
Now the
SELECT t FROM Thread t, ThreadKeyword tk WHERE t.id = tk.id.threadId
works fine because Hibernate knows how to translate the query you have there into SQL.

Categories

Resources