package net.roseindia.hqlexamples;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import net.roseindia.model.*;
/**
* HQL Select Example In this example we are selecting all the customers from
* the datastore
*/
public class HQLSelect {
public static void main(String[] args) throws Exception {
/** Getting the Session Factory and session */
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.getCurrentSession();
/** Starting the Transaction */
Transaction tx = session.beginTransaction();
// Create Select Clause HQL
String HQL_QUERY = "select c from Customer c";
Query query = session.createQuery(HQL_QUERY);
List result = query.list();
for (Iterator it = result.iterator(); it.hasNext();) {
Customer customer = (Customer) it.next();
System.out.println("ID: " + customer.getId());
System.out.println("Name: " + customer.getCustomerName());
System.out.println("Phone: " + customer.getCustomerPhone());
}
/** Closing Session */
session.close();
}
}
log4j.properties
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=warn, stdout
package net.roseindia.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.GeneratedValue;
/**
* @author Deepak Kumar
* Hibernate HQL Tutorials
*/
@Entity
@Table(name="customers")
public class Customer {
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name="customer_name")
private String customerName;
@Column(name="customer_phone")
private String customerPhone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerPhone() {
return customerPhone;
}
public void setCustomerPhone(String customerPhone) {
this.customerPhone = customerPhone;
}
}
源代码:http://pan.baidu.com/share/link?shareid=421815&uk=3878681452
原文:http://www.roseindia.net/hibernate/examples/hql/HQL-Select.html