增删改查
一、 添加数据
public void addNews(News news) {
// TODO Auto-generated method stub
Session session =HibernateUtil.getSession();
Transaction tran = session.beginTransaction()开始事物
session.save(news);//执行
tran.commit();//提交
根据id删除数据
Session session =HibernateUtil.getSession();
Transaction tran = session.beginTransaction();//开始事物
News news =(News) session.load(News.class, nid);
session.delete(news);
tran.commit();//提交
修改数据根据id修改
1、Session session = null;
try {
session =HibernateUtil.getSession();
session.beginTransaction();
News news=(News) session.load(News.class, id);
news.setMark(mark);
session.update(news);
session.getTransaction().commit();
}catch (RuntimeException re) {
throw re;
} finally {
HibernateUtil.closeSession();
}
2.修改 注意:该方法需修改*.Hbm.xml配置文件,默认根据id修改
<property name="ncity" type="string" update = "false">
那个字段不用修改加上update=”false”
Session session=null;
Transaction tx=null;
try {
session =HibernateUtil.getSession();
tx=HibernateUtil.getSession().beginTransaction();
session.update(news); //修改数据
tx.commit();
} catch (RuntimeException re) {
throw re;
} finally {
HibernateUtil.closeSession();
}
查询 根据id查询
public News findById(Integer nid) {
// TODO Auto-generated method stub
try {
News instance=(News) HibernateUtil.getSession().get("bean.News", nid);
return instance;
} catch (RuntimeException re) {
throw re;
} finally {
HibernateUtil.closeSession();
}
}
根据输入的字段查询全部propertyName为字段名
public List<News> findByProperty(String propertyName, Object value) {
// TODO Auto-generated method stub
try {
String queryString = "from News as n where n." + propertyName + "= ?";
Query queryObject = HibernateUtil.getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
throw re;
} finally{
HibernateUtil.closeSession();
}
}
查询全部
public List<Toupiao> findAll() {
// TODO Auto-generated method stub
try {
String queryString = "from Toupiao";
Query queryObject = getSession().createQuery(queryString);
queryObject.setMaxResults(100);
return queryObject.list();
} catch (RuntimeException re) {
throw re;
} finally{
closeSession();
}
}