Hibernate4详解(十一)

2014-11-24 10:41:08 · 作者: · 浏览: 12

Transaction tx = session.beginTransaction();
session.persist(customer); // 无返回值
tx.commit();
session.close();
}

// 添加
@Test
public void test_saveOrUpdate1() {
Customer customer = new Customer();
customer.setName("monday");

SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(customer); // OID 为空 执行save操作
tx.commit();
session.close();
}

// 修改
@Test
public void test_saveOrUpdate2() {
Customer customer = new Customer();
customer.setName("monday_update");
customer.setId(5);

SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(customer); // OID 为不空 执行update操作
tx.commit();
session.close();
}

// 修改
@Test
public void test_update() {
Customer customer = new Customer();
customer.setName("monday_update2");
customer.setId(5);

SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.update(customer);
tx.commit();
session.close();
}

// 修改
@Test
public void test_update_hql() {
String hql = "update Customer set name= where id= ";
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(hql);
query.setParameter(0, "springfuncs");
query.setParameter(1, 5);
query.executeUpdate();
tx.commit();
session.close();
}

// 删除
@Test
public void test_delete() {
Customer customer = new Customer();
customer.setId(5);

SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.delete(customer);
tx.commit();
session.close();
}

// 删除
@Test
public void test_delete_hql() {
String hql = "delete from Customer where id= ";
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery(hql);
query.setParameter(0, 6);
query.executeUpdate();
tx.commit();
session.close();
}

// 查询
@Test
public void test_get() {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
// Transaction tx = session.beginTransaction();
Customer customer = (Customer) session.get(Customer.class, 1);
// tx.commit();
session.close();
System.out.println(customer);
}

// 查询
@Test
public void test_