HQL查询依赖于Query类,每个Query实例对应一个查询对象,使用HQL查询按如下步骤进行:
1.获取Hibernate Session对象
2.编写HQL语句
3.以HQL语句作为参数,调用Session的createQuery方法创建查询对象
4.如果HQL语句包含参数,则调用Query的setXxx方法为参数赋值
5.调用Query独享的list()或uniqueResult()方法返回查询结果列表
简单的例子:
@SuppressWarnings(“deprecation”)
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
public static Session getOpenSession() {
return sessionFactory.openSession();
}
public static Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}
@Entity
public class Employee {
private Integer id;
private String name;
private Integer age;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String toString() {
return “id:” + id + ” ” + “name:” + name + ” ” + “age:” + age;
}
}
@SuppressWarnings(“all”)
public class HQLDemo {
@Test
public void testHQL() {
Session session = HibernateUtil.getOpenSession();
List<Employee> employeeList = session.createQuery(“from Employee as e”).list();
for(Employee e : employeeList)
System.out.println(e);
}
@Test
public void testHQLHasParameter() {
Session session = HibernateUtil.getOpenSession();
List<Employee> employeeList = session.createQuery(“from Employee as e where e.name = :personName”).setString(“personName”, “xujianguo”).list();
for(Employee e : employeeList)
System.out.println(e);
}
}
原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/236675.html