It is believed that the brothers who have used hibernate will fret about how the returned results are assembled into a VO because of the complex query of multiple tables. I also keep worrying about it, but after watching Hibernate's transform, I feel that this method works.
For example, now there are two tables, one is the user table, put some information about users, and the other table is a user post, inside there is a foreign key for users. We need to query out the post that someone posted, SQL is as follows:
Java code
Select U.username,p.title,p.addtime from user as u,post as P where U.id=p.userid
But our Pojo mapping is only to do the User,post table mapping, this time, we need to write a Postvo class, inside the user's information and information about the properties of the post, set the Get\set method, It is important to ensure that the class has a default constructor.
Then we start writing the DAO for this database operation, the code is as follows:
Java code
,addtime from user as u,post as P where u.id=p.userid "Query q = factory.getcurrentsession (). Create SQLQuery (SQL). Setresulttransformer (Transformers.aliastobean (Postvo.class));
The Scarlet Letter part must be followed by the attribute in Postvo, so that a collection of Postvo can be returned.
In fact, we can see hibernate this part of the source code will be found, mainly using Aliastobeanresulttransformer this class, through the SQL query, will return the array, and hibernate according to the data table mapping, Automatically help us to set the corresponding field properties, so the red part must be with the attribute value in Vo has been, or will error.
You can also rewrite this class if you need to. such as Voresulttransformer. Then change it in DAO to
Java code
Setresulttransformer (New Voresulttransformer (Postvo.class));
Can.
About hibernate Pure SQL queries returning result sets (do not write multiple table associations in Hbm.xml)