Exemplo n.º 1
0
  // 添加
  @Test
  public void test_saveOrUpdate1() {
    Customer customer = new Customer();
    customer.setName("monday#test_saveOrUpdate1");

    // SessionFactory sessionFactory =
    // HibernateUtils.getSessionFactory();//方式一:没有整合Spring+Hibernate时,需要使用hibernate.cfg.xml手动创建
    SessionFactory sessionFactory =
        hibernateTemplate.getSessionFactory(); // 方式二:整合Spring+Hibernate成功后,可以从Spring容器中直接获取Bean
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    session.saveOrUpdate(customer); // OID 为空 执行save操作
    tx.commit();
    session.close();
  }
Exemplo n.º 2
0
  // 删除
  // 因为与其他测试方法存在冲突,需要独立测试(请先注释其他测试方法),测试才会通过
  @Test
  public void test_delete() {
    Customer customer = new Customer();
    customer.setId(5);

    // SessionFactory sessionFactory =
    // HibernateUtils.getSessionFactory();//方式一:没有整合Spring+Hibernate时,需要使用hibernate.cfg.xml手动创建
    SessionFactory sessionFactory =
        hibernateTemplate.getSessionFactory(); // 方式二:整合Spring+Hibernate成功后,可以从Spring容器中直接获取Bean
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    session.delete(customer);
    tx.commit();
    session.close();
  }
Exemplo n.º 3
0
  // 添加
  @Test
  public void test_save() {

    Customer customer = new Customer();
    customer.setName("monday#test_save");

    // SessionFactory sessionFactory =
    // HibernateUtils.getSessionFactory();//方式一:没有整合Spring+Hibernate时,需要使用hibernate.cfg.xml手动创建
    SessionFactory sessionFactory =
        hibernateTemplate.getSessionFactory(); // 方式二:整合Spring+Hibernate成功后,可以从Spring容器中直接获取Bean
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    Serializable id = session.save(customer); // 返回OID
    tx.commit();
    session.close();
    System.out.println("id=" + id);
  }