Copy the code code as follows:
package com.zxd.test;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.zxd.bean.House;
import com.zxd.util.QueryProperty;
/**
* Test class for HQL closed query
* @author zhang
*
*/
public class TestHouse {
public static void main(String[] args) {
//Public member variables
SessionFactory sf = null;
Session session = null;
QueryProperty qp = new QueryProperty();
//Encapsulate the query data
qp.setTitle("%好房%");
qp.setStreet_id("1002");
qp.setType_id("1004");
qp.setLow_price(20);
qp.setHigh_price(200);
qp.setSmall_floorage(50);
qp.setBig_floorage(180);
//HQL statement
StringBuffer sb = new StringBuffer();
sb.append("from House where ");
sb.append("(title like :title) ");
sb.append("and (type_id like :type_id) ");
sb.append("and (street_id like :street_id) ");
sb.append("and (price between :low_price and :high_price) ");
sb.append("and (floorage between :small_floorage and :big_floorage)");
try {
//Start executing the query
sf = new Configuration().configure().buildSessionFactory();
session = sf.openSession();
Query query = session.createQuery(sb.toString());
query.setProperties(qp);
List<House> list = query.list();
//The first type uses: loop
/*for(House house:list){
System.out.println("The title is: "+house.getTitle());
System.out.println("The area is: "+house.getFloorage());
System.out.println("The price is: "+house.getPrice());
System.out.println("District is: "+house.getStreet().getDistrict().getName());
System.out.println("The street is: "+house.getStreet().getName());
System.out.println("----------------------------------");
}*/
//Second loop
for(int i = 0;i<list.size();i++){
System.out.println("The title is: "+list.get(i).getTitle());
System.out.println("The area is: "+list.get(i).getFloorage());
System.out.println("The price is: "+list.get(i).getPrice());
System.out.println("District is: "+list.get(i).getStreet().getDistrict().getName());
System.out.println("The street is: "+list.get(i).getStreet().getName());
System.out.println("----------------------------------");
}
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
session.close();
sf.close();
}
}
}
The first type of loop in the above example is something I didn't remember. It uses the key character ":". Generally, this type of loop is used to traverse a collection (List<House>, Map). convenient.
The second type of loop is an ordinary loop. This is the most common for loop in Java.