There are two ways to fetch in field mappings in Hibernate: Eager and lazy
Eager: Crawl All
Lazy: Lazy Crawl
If declared as eager in the field, the associated bean values in the bean are also fetched when the current bean is acquired. That is, database queries multiple times. Instead, lazy then crawls the commit query.
For example, there are user beans that are declared as eager:
@OneToMany (mappedby= "User", Cascade=cascadetype.all, Fetch=fetchtype. EAGER) private set<usercard> cards;
When a join query is used, the cards under the user bean are queried together:
// ---------------------------------------------------- //Left join// ----------------------------------------------------String hql = "Select U from the User u left JOIN u.cards C WHERE u.username=:username and C.cardid=:cardid"; Query Query=session.createquery (HQL); Query.setlong ("CardID", 1); Query.setstring ("UserName", "Robin"); List<User> users =query.list (); for(User user:users) {System.out.println ("User ID:" +User.getuserid ()+ "\tuser Name:" +user.getusername ()); }
SQL and query results for output:
If you change the eager to lazy:
@OneToMany (mappedby= "User", Cascade=cascadetype.all, Fetch=fetchtype. LAZY) private set<usercard> cards;
Inquire:
---------------------------------------------------- //LEFT JOIN //---------------------------------- ------------------ String hql = "Select U from the User u left JOIN u.cards C WHERE u.username=:username and C.cardid=:car Did "; Query query = session.createquery (HQL); Query.setlong ("CardID", 1); Query.setstring ("UserName", "Robin"); list<user> users = query.list (); For (user user:users) {System.out.println ("User ID:" + User.getuserid () + "\tuser Name:" + User.getusern Ame ()); }
SQL and query results for output:
Of course, in most cases, the bean design should be lazy.
Because if you really want to synchronize the query to get the value of the associated object bean, you can do so by adding the FETCH keyword to the HQL.
Fetch Reference Example: http://www.cnblogs.com/HD/p/3957926.html
Using fetch, as above query hql can be written as:
FETCH JOIN u.cards C WHERE u.username=:username and C.cardid=:cardid ";
[Hibernate]-EAGER and LAZY