首页 > Web开发 > 详细

hibernate更新的小知识

时间:2016-04-21 18:41:59      阅读:205      评论:0      收藏:0      [点我收藏+]
	private static void test5() {
		SessionFactory sessionFactory = new Configuration().configure()
				.buildSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction().begin();
		int i = session.createQuery(
				"update UserInfo set loginName=concat(loginName" + ",‘yjmfsaf‘)"
						+ " where uid=" + "‘4028e5734d2c1726014d2c172bdb0001‘")
				.executeUpdate();
		System.out.println(i);

	}


Hibernate: update t_userinfo set t_loginname=concat(t_loginname, ‘yjmfsaf‘) where uid=‘4028e5734d2c1726014d2c172bdb0001‘

1


测试,将某个字段的值更新等于字段值+字符串。不用先根据ID 查出来然后再更赋值更新。


想做批量数据处理,根据ID 有就更新,没有就插入。


用saveOrUpdate hibernate 根据对象的主键来判断,有主键值就走更新,主键是自动生成更新就报错不走保存,主键值是 指派的  没有主键值没有更新成功就走保存。



merge 就是先查询 有就走更新,没有就走 insert 没有对象 持久 临时 游离之分 不分主键是否自动生成还是指定


不如先更新 ,返回行数1就不用走 insert了,返回0就走insert不用 select了。

hibernate提供的方法满足不了需求,就用HQL了。




private static void test3() {

SessionFactory sessionFactory = new Configuration().configure()

.buildSessionFactory();

Session session = sessionFactory.openSession();

session.beginTransaction().begin();

UserInfo userInfo = new UserInfo();

userInfo.setLoginName("test..info..._sdfsdupdate1");

userInfo.setUid("4028e7a154380a0b0154380a01c630001343434");

session.saveOrUpdate(userInfo);

session.getTransaction().commit();


// Session session1 = sessionFactory.openSession();

// session.beginTransaction().begin();

// session.saveOrUpdate(userInfo);

// session.getTransaction().commit();

}


hibernate更新的小知识

原文:http://yjm199.blog.51cto.com/4408395/1766306

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!