Method Example of Querying All and Partial Data Using HQLQuery in Hibernate
- 2021-07-10 19:48:57
- OfStack
As for the HQL we learn, I probably understand it as a query language, which has no effect of adding, deleting and modifying, while the operation we use for query feels very simple to use, with little code and easy to understand.
The following is a simple example of a query operation
package com.lc.view;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.lc.domain.Student;
import com.lc.utils.HibernateUtil;
public class selectStudent {
public static void main(String[] args) {
selectSomeStudents();
}
/**
* 1. Retrieve all students
**/
public static void selectAllStudents(){
Session session = null;
Transaction ts = null;
try {
session = HibernateUtil.getCurrentSession();
ts = session.beginTransaction();
List<Student> list = session.createQuery("from Student").list();
// Fetch data 1.for Cyclic enhancement
for(Student stu:list){
System.out.println(stu.getSid()+" "+ stu.getSname()+" "+stu.getSdept());
}
// Fetch data 2. Iterator
System.out.println("------------------------------");
Iterator iterator = list.iterator();
while(iterator.hasNext()){
Student s = (Student) iterator.next();
System.out.println(s.getSid()+" "+ s.getSname()+" "+s.getSdept());
}
ts.commit();
} catch (Exception e) {
if (ts != null) {
ts.rollback();
}
throw new RuntimeException(e.getMessage());
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
/**
* 2. Retrieve the students in the section
**/
public static void selectSomeStudents(){
Session session = null;
Transaction ts = null;
try {
session = HibernateUtil.getCurrentSession();
ts = session.beginTransaction();
/**
* You can't remove the data like this Because only Student Two property values of the object No 1 Objects
List<Student> list = session.createQuery("select sname,sdept from Student").list();
for(Student stu:list){
System.out.println(stu.getSname()+" "+stu.getSdept());
}**/
List list = session.createQuery("select sname,sdept from Student").list();
for(int i=0;i<list.size();i++){
Object[] obj = (Object[]) list.get(i);
System.out.println(obj[0].toString()+" "+obj[1].toString());
}
ts.commit();
} catch (Exception e) {
if (ts != null) {
ts.rollback();
}
throw new RuntimeException(e.getMessage());
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
}
Summarize