码迷,mamicode.com
首页 > 其他好文 > 详细

Hql 执行CRUD

时间:2015-01-31 14:20:03      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

	//新增]
	@Test
	public void add(){
	config = new Configuration();
	sessionfactory = config.configure("hibernate.cfg.xml").buildSessionFactory();
	session = sessionfactory.openSession();
	ts = session.beginTransaction();
	User user = new User();
	user.setName("QQ");
	user.setPwd("123");
	session.save(user);
	ts.commit();
	session.close();
}

 

	//HQL 查询-----------------------------
	@Test
	public void sel(){
		config = new Configuration();
		sessionfactory = config.configure("hibernate.cfg.xml").buildSessionFactory();
		session = sessionfactory.openSession();
		ts = session.beginTransaction();
		Query query = session.createQuery("from User user where user.name=? and user.pwd=?");
		query.setString(0, "www");
		query.setString(1, "888");
		List uu = (List) query.list();		
		for(int i =0;i<uu.size();i++){
			User user = (User) uu.get(i);
			System.out.println(user.getName() +"-------"+ user.getPwd());
		}
		session.close();
	}

 

	//HQL 删除
	@Test
	public void del(){
		 config = new Configuration();
		 sessionfactory = config.configure("hibernate.cfg.xml").buildSessionFactory();
		 session = sessionfactory.openSession();
		 ts = session.beginTransaction();
		 String hql="delete from User user where user.id=?";
		 Query queryupdate=session.createQuery(hql);
		 queryupdate.setInteger(0, 5);
		 int ret=queryupdate.executeUpdate();
		 if(ret >0 ){
			 System.out.println("删除成功");
		 }else{
			 System.out.println("删除失败");
		 }
		 
ts.commit();
}

 

	//HQL 修改 -----------------------------------------
	@Test
	public void update(){
		config = new Configuration();
		 sessionfactory = config.configure("hibernate.cfg.xml").buildSessionFactory();
		 session = sessionfactory.openSession();
		 ts = session.beginTransaction();
		 String hql = "update User user set user.name=?,user.pwd=? where user.id=?";
		 Query queryupdate=session.createQuery(hql); 
		 queryupdate.setString(0, "ABCDE");
		 queryupdate.setString(1, "AAA");
		 queryupdate.setInteger(2,6);
		 int ret=queryupdate.executeUpdate(); 
		 if(ret >0 ){
			 System.out.println("修改成功");
		 }else{
			 System.out.println("修改失败");
		 }
		 ts.commit();
	}

 

Hql 执行CRUD

标签:

原文地址:http://www.cnblogs.com/sunxun/p/4263945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!