首页 > 代码库 > Hibernate 中对表的操作
Hibernate 中对表的操作
Hibernate CRUD testing
Hibernate 中对表的操作, add,load,update,delete,list,pager(分页)
package org.test.test; import java.text.SimpleDateFormat; import java.util.List; import org.hibernate.Session; import org.junit.Test; import org.zttc.itat.model.User; import org.zttc.itat.util.HibernateUtil; @SuppressWarnings("unchecked") public class TestCRUD { private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); @Test public void testAdd() { Session session = null; try { session = HibernateUtil.openSession(); session.beginTransaction(); User u = new User(); u.setBorn(sdf.parse("1977-11-22")); u.setNickname("张老七"); u.setPassword("123"); u.setUsername("zhanglaowu"); session.save(u); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); if(session!=null) session.getTransaction().rollback(); } finally { HibernateUtil.close(session); } } @Test public void testLoad() { Session session = null; try { session = HibernateUtil.openSession(); User u = (User)session.load(User.class,2); System.out.println(u); } catch (Exception e) { e.printStackTrace(); } finally { HibernateUtil.close(session); } } @Test public void testUpdate() { Session session = null; try { session = HibernateUtil.openSession(); session.beginTransaction(); User u = (User)session.load(User.class, 2); u.setNickname("张小四"); session.update(u); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); if(session!=null) session.getTransaction().rollback(); } finally { HibernateUtil.close(session); } } @Test public void testDelete() { Session session = null; try { session = HibernateUtil.openSession(); session.beginTransaction(); User u = new User(); u.setId(2); session.delete(u); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); if(session!=null) session.getTransaction().rollback(); } finally { HibernateUtil.close(session); } } @Test public void testList() { Session session = null; try { session = HibernateUtil.openSession(); List<User> users = session.createQuery("from User").list(); for(User u:users) { System.out.println(u); } } catch (Exception e) { e.printStackTrace(); } finally { HibernateUtil.close(session); } } @Test public void testPager() { Session session = null; try { session = HibernateUtil.openSession(); List<User> users = session.createQuery("from User") .setFirstResult(0) .setMaxResults(2).list(); for(User u:users) { System.out.println(u); } } catch (Exception e) { e.printStackTrace(); } finally { HibernateUtil.close(session); } } }
Hibernate 中对表的操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。