一、首先要继承HibernateDaoSupport类。
先将要修改的数据保存到对象中,将对象传给方法
public ClientClick saveClientClick(ClientClick clientClick) {
try {
this.getHibernateTemplate().saveOrUpdate(clientClick);
return clientClick;
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
二、XML中设置property 标签 update = "false" ,如下:我们设置 age 这个属性在更改中不做更改
view plaincopy to clipboardprint?
<property name="age" update="false"></property>
<property name="age" update="false"></property>
在Annotation中 在属性GET方法上加上@Column(updatable=false)
view plaincopy to clipboardprint?
@Column(updatable=false)
public int getAge() {
return age;
}
@Column(updatable=false)
public int getAge() {
return age;
}
我们在执行 Update方法会发现,age 属性 不会被更改
view plaincopy to clipboardprint?
Hibernate:
update
Teacher
set
birthday=?,
name=?,
title=?
where
id=?
Hibernate:
update
Teacher
set
birthday=?,
name=?,
title=?
where
id=?
缺点:不灵活····
三、使用XML中的 dynamic-update="true"
view plaincopy to clipboardprint?
<class name="com.sccin.entity.Student" table="student" dynamic-update="true">
<class name="com.sccin.entity.Student" table="student" dynamic-update="true">
OK,这样就不需要在字段上设置了。
但这样的方法在Annotation中没有
四、使用HQL语句(灵活,方便) 使用HQL语句修改数据
public int updateClientClick(String hardware, String feetime,long effectTimes,
long desktopCount, long floatCount, long backCount,
long shortCutCount, long netCount, long gameCount,
long startOpenCount) {
String sql="update ClientClick set effectTimes=effectTimes+?,desktopCount=desktopCount+?,floatCount=floatCount+?," +
"backCount=backCount+?,shortCutCount=shortCutCount+?,netCount=netCount+?,gameCount=gameCount+?,startOpenCount=startOpenCount+?" +
" where hardware=? and feeTime=?";
/*String sql="update ClientClick set effectTimes=effectTimes+"+effectTimes+",desktopCount=desktopCount+"+desktopCount+",floatCount=floatCount+"+floatCount+"," +
"backCount=backCount+"+backCount+",shortCutCount=shortCutCount+"+shortCutCount+",netCount=netCount+"+netCount+",gameCount=gameCount+"+gameCount+",startOpenCount=startOpenCount+"+startOpenCount+"" +
" where hardware="+hardware+" and feeTime="+feetime+"";*/
Session session = getHibernateTemplate().getSessionFactory().openSession();
Query query = null;
session.beginTransaction();
query = session.createQuery(sql);
//若是拼串的形式就不需要以下的传值过程
query.setLong(0, effectTimes);
query.setLong(1, desktopCount);
query.setLong(2, floatCount);
query.setLong(3, backCount);
query.setLong(4, shortCutCount);
query.setLong(5, netCount);
query.setLong(6, gameCount);
query.setLong(7, startOpenCount);
query.setString(8, hardware);
query.setString(9, feetime);
query.executeUpdate();
session.getTransaction().commit();
return query.executeUpdate();
}