Hibernate增删改查方法
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import java.util.List;
import org.hibernate.Query;
import java.util.Iterator;
public class HbmTestDao {
private static SessionFactory sessionFactory = null;
private Session session = null;
Transaction transaction = null;
static{
try{
sessionFactory = new Configuration().configure().buildSessionFactory();
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 查询方法
* @return
*/
public List selectTb(){
List list = null;
session = sessionFactory.openSession();
transaction = session.beginTransaction();
String hql = "from Test";
try{
Query query = session.createQuery(hql);
list = query.list();
}catch(Exception e){
e.printStackTrace();
}
transaction.commit();
session.close();
return list;
}
/**
* 模糊查询;
*/
public List selectByName(String name){
List it = null;
String hql = "select user from Test as user where user.name like:name";
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Query query = session.createQuery(hql);
query.setString("name","%"+name+"%");
it = query.list();
transaction.commit();
session.close();
return it;
}
/**
* 根据ID查询
*/
public List selById(Integer id){
List list = null;
String hql = "from Test where id = "+id;
session = sessionFactory.openSession();
Query query = session.createQuery(hql);
//query.setInteger("id",id.intValue());
list = query.list();
session.beginTransaction().commit();
session.close();
return list;
}
/**
* 插入方法;
*/
public int insertTb(Test test){
int i=0;
session = sessionFactory.openSession();
try{
session.beginTransaction();
session.save(test);
session.beginTransaction().commit();
i=1;
}catch(Exception e){
e.printStackTrace();
}
session.close();
return i;
}
/**
* 删除方法;
*/
public int DelTb(Integer id){
int i = 0;
session = sessionFactory.openSession();
try{
session.beginTransaction();
Test test = (Test)session.get(Test.class,id);
session.delete(test);
session.beginTransaction().commit();
session.close();
i = 1;
}catch(Exception e){
e.printStackTrace();
}
return i;
}
/**
* 更新方法;
*/
public int UpTb(Test test){
int i = 0;
session = sessionFactory.openSession();
try{
session.beginTransaction();
session.update(test);
session.beginTransaction().commit();
session.close();
i = 1;
}catch(Exception e){
e.printStackTrace();
}
return i;
}
}