Hibernate关于的Timestamp的问题

来源:互联网 发布:光纤三端口环形器原理 编辑:程序博客网 时间:2024/05/21 11:07
计算商品的点击次数的需求

1、更新商品的点击次数
2、并且返回当前商品

问题描述:
当执行完操作后
private Timestamp pushDate; //入库时间(import java.sql.Timestamp;)
这个映射字段每次都会被重置为当前时间,譬如 2015-12-25 16:27:49


原因:
一个session里面是有实体的生命周期的,在这个周期内,实体的所有值得变化都会反映到数据库里面,最后事物提交了就会出问题。
解决办法:分开写两个业务,一个增加点击量,一个返回详情;用hibernate更新的时候最好先查询出来这个实体,然后对实体设置变化值,
最后更新到数据库,这样可以避免很多问题。

余留问题:
直接书写sql语句,对于Timestamp类型的映射值来说还是会出问题,就是这一点不懂,还望大大解答。

原来的代码:
@Overridepublic Goods getExgProductContent(String gid) {Session session = hib.getSession();Transaction tx=session.beginTransaction();try{Goods goods=(Goods) session.get(Goods.class, gid);//更新点击次数String sql="update tablename set click_count=:clickCount where g_id=:gid";Query query=session.createSQLQuery(sql);query.setParameter("gid", gid);query.setParameter("clickCount", goods.getClickCount()+1);query.executeUpdate();tx.commit();return goods;}catch(Exception e){//e.getMessage();KeyhuaLogger.logger.debug(e.getMessage());tx.rollback();return null;}finally{if(null!=session) session.close();}}


修改后的代码:


@Overridepublic Goods getExgProductContent(String gid) {Session session = hib.getSession();try{//得到商品Goods goods=(Goods)session.createSQLQuery("select * from tablename where g_id=?").addEntity(Goods.class).setString(0, gid).uniqueResult();return goods;}catch(Exception e){e.printStackTrace();return null;}finally{if(null!=session) session.close();}}@Overridepublic void addClickCount(String gid) {Session session = hib.getSession();Transaction tx=session.beginTransaction();try{//更新点击次数Goods goods=(Goods) session.get(Goods.class, gid);goods.setClickCount(goods.getClickCount()+1);session.save(goods);tx.commit();}catch(Exception e){e.printStackTrace();}finally{if(null!=session) session.close();}}


0 0
原创粉丝点击