日期:2014-05-16  浏览次数:20544 次

hibernate数据库查找
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import junit.framework.TestCase;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.java.Student;
import cn.util.HibernateUtil;

public class TestQuest2 extends TestCase{
public void test(){
Session session = null;
Transaction tx = null;

try{

session = HibernateUtil.getSession();
tx = session.beginTransaction();
//给给它传送个值id=2
Student s = (Student)session.createQuery("from Student s where s.id= ?")
.setParameter(0, 2)
.uniqueResult();
System.out.println(s.getName());
//============================================================
//查找id>10的数据
List<Student>list = session.createQuery("from Student s where s.id >?")
.setParameter(0, 10)
.list();
for(Student s : list){
System.out.println(s.getName());
}
//===================================================================
//根据命名来查找的
List<Student>list = session.createQuery("from Student s where s.name = :setname")
.setParameter("setname", "jerry9")
.list();
for(Student s : list){
System.out.println(s.getName());
System.out.println(s.getCreateTime());
}
//============================================================================
//模糊查询
List<Student> list = session.createQuery("from Student s where s.name like ?")
.setParameter(0, "j%")
.list();
for(Student s : list){
System.out.println(s.getName());
}

List<Student> ls = session.createQuery("from Student s where s.id in (:myids)")
.setParameterList("myids", new Object[]{1, 3, 5})
.list();
    for(Student s:ls){
System.out.println(s.getName());
System.out.println(s.getCreateTime());

==============================查找日期
List<Student> ls = session.createQuery("from Student s where s.createTime between ?  and  ?")
.setParameter(0, convert("2009-09-27"))
.setParameter(1, convert("2009-09-28"))
.list();

for(Student s:ls){
System.out.println(s.getName());
System.out.println(s.getCreateTime());
}
session.getTransaction().commit();
} catch (HibernateException e) {
e.printStackTrace();
} finally {
HibernateUtil.close(session);
}
   }


Query query = session.createQuery("from Student");
List<Student>list = query.list();
for(Student s : list){
System.out.println(s.getName());
}

Query query = session.createQuery("select s from Student as s");
List<Student>list = query.list();
for(Student s : list){
System.out.println(s.getName());
}

//================================================================
Query query = session.createQuery("select count(*)from Student");
//返回一个结果
Long l = (Long)query.uniqueResult();
System.out.println(l);

Query query = session.createQuery("select s.id,s.name from Student as s");
//返回值是一个结果...
        List<Object[]> os = query.list();
        for(int i = 0 ; i < os.size();i++){
        Object [] oss = os.get(i);
        for(int j = 0; j < oss.length;j++){
System.out.print("...第"+j+"个元素"+oss[j]);
       }
       System.out.println();