Use of Returning multiple entities in SQL by R4R Team

Here till now result set column names are assumed to be the same as the column names specified in the mapping document. This can be problematic for SQL queries that join multiple tables, since the same column names can appear in more than one table.

Column alias injection is needed in the following query (which most likely will fail):

sess.createSQLQuery("SELECT c.*, m.*  FROM STUDENTS c, STUDENTS m WHERE c.MOTHER_ID = c.ID")
 .addEntity("student", Student.class)
 .addEntity("mother", Student.class)

The query was intended to return two Student instances per row: a cat and its mother. The query will, however, fail because there is a conflict of names; the instances are mapped to the same column names. Also, on some databases the returned column aliases will most likely be on the form "c.ID", "c.NAME", etc. which are not equal to the columns specified in the mappings ("ID" and "NAME").

The following form is not vulnerable to column name duplication:

sess.createSQLQuery("SELECT {student.*}, {mother.*}  FROM STUDENTS c, STUDENTS m WHERE c.MOTHER_ID = c.ID")
 .addEntity("student", Student.class)
 .addEntity("mother", Student.class)

This query specified:

1. the SQL query string, with placeholders for Hibernate to inject column aliases
2. the entities returned by the query

The {student.*} and {mother.*} notation used above is a shorthand for "all properties". Alternatively, you can list the columns explicitly, but even in this case Hibernate injects the SQL column aliases for each property. The placeholder for a column alias is just the property name qualified by the table alias. In the following example, you retrieve Cats and their mothers from a different table (student_log) to the one declared in the mapping metadata. use the property aliases in the where clause.

String sql = "SELECT ID as {c.id}, NAME as {c.name}, " + 
         "BIRTHDATE as {c.birthDate}, MOTHER_ID as {c.mother}, {mother.*} " +
         "FROM STUDENT_LOG c, STUDENT_LOG m WHERE {c.mother} = c.ID";

List loggedStudents = sess.createSQLQuery(sql)
        .addEntity("student", Student.class)
        .addEntity("mother", student.class).list()
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!