package com.test;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.hibernate.Usertest.Usertest;
public class Test {
public static void main(String[] args) {
String hql="from Usertest where id=?";
String[] parm={"2"};
List<Usertest> list=chaxun(hql,parm);
for(Usertest u:list){
System.out.println(u.getId()+"/"+u.getName()+"/"+u.getPassword());
}
}
//添加
public static void tianjia(Usertest um) {
SessionFactory sf = new Configuration().configure()
.buildSessionFactory();
Session s = null;
Transaction t = null;
try {
// 准备数据
s = sf.openSession();
t = s.beginTransaction();
s.save(um);
t.commit();
} catch (Exception err) {
t.rollback();
err.printStackTrace();
} finally {
s.close();
}
}
//查询
public static List<Usertest> chaxun(String hql,String[] parm){
List<Usertest> list=null;
SessionFactory sf = new Configuration().configure()
.buildSessionFactory();
Session s = null;
try {
s = sf.openSession();
Query query=s.createQuery(hql);
if(parm!=null&&parm.length>0){
for(int i=0;i<parm.length;i++){
query.setString(i,parm[i]);
}
}
list=query.list();
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
}