hibernate以其出色的映射机制,实现了对象与关系数据库中的数据之间的自由转化,可通过对持久化对象进行操作来完成对数据库中数据的操作。大大减少了代码编写的工作量,深受开发人员的喜爱。

    修改数据库是一个常见的操作,在hibernate中我们可以通过如下几种方式来进行修改操作。

  1. 修改全部字段。

    在建立实体类的基础上,我们只需简单的调用如下update()方法就可实现对数据库对应表的修改。

public void update(Object obj) throws HibernateException{
		Session session=HibernateSessionFactory.getSession();
		Transaction tran=null;
		try{
			tran=session.beginTransaction();
			session.update(obj);
			tran.commit();
		}catch(HibernateException e){
			if(tran!=null)tran.rollback();
			throw e;
		}finally{
			session.close();
		}
	}

2.一些特殊的字段不需要修改

    实际开发中一些特殊的字段不需要修改,如信息采集时间,录入时间等信息,一旦录入就不需要修改了,在hibernate中我们只需简单的配置一下就可实现。

<property name="entryTime" update="false"></property> 

当然也可以采用注释的方法,在get方法上加上@Column(updatable=false)

3.只对自己指定的字段进行修改

    此时我们就可以用HQL语句自由地进行修改了:

public boolean buidingupdate(int buildingId,StringbuildingName,String propertyAdress){
        Object[] o={ buildingName,propertyAdress,buildingId};
        String hql="update Building set propertyAdress=?,buildingName=? where buildingId = ?";
        hds.batchUpdate(hql,o);
        return true;
    }
public int batchUpdate(String hql,Object[] params){
		int ret=0;
		Session session=HibernateSessionFactory.getSession();
		Transaction t=null;;
		try{
			Query q=session.createQuery(hql);
			t=session.beginTransaction();
			if(params!=null){
				for(int i=0;i<params.length;i++){
					q.setParameter(i, params[i]);
				}
			}
			ret=q.executeUpdate();
			t.commit();
		}catch(HibernateException e){
			if(t!=null) t.rollback();
			throw e;
		}finally{
			session.close();
		}
		return ret;
	}
}