public void testGetLoad() {
    clearCounts();

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    Employer emp = new Employer();
    s.persist(emp);
    Node node = new Node("foo");
    Node parent = new Node("bar");
    parent.addChild(node);
    s.persist(parent);
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.get(Employer.class, emp.getId());
    assertTrue(Hibernate.isInitialized(emp));
    assertFalse(Hibernate.isInitialized(emp.getEmployees()));
    node = (Node) s.get(Node.class, node.getName());
    assertTrue(Hibernate.isInitialized(node));
    assertFalse(Hibernate.isInitialized(node.getChildren()));
    assertFalse(Hibernate.isInitialized(node.getParent()));
    assertNull(s.get(Node.class, "xyz"));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.load(Employer.class, emp.getId());
    emp.getId();
    assertFalse(Hibernate.isInitialized(emp));
    node = (Node) s.load(Node.class, node.getName());
    assertEquals(node.getName(), "foo");
    assertFalse(Hibernate.isInitialized(node));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.get("org.hibernate.ejb.test.ops.Employer", emp.getId());
    assertTrue(Hibernate.isInitialized(emp));
    node = (Node) s.get("org.hibernate.ejb.test.ops.Node", node.getName());
    assertTrue(Hibernate.isInitialized(node));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    emp = (Employer) s.load("org.hibernate.ejb.test.ops.Employer", emp.getId());
    emp.getId();
    assertFalse(Hibernate.isInitialized(emp));
    node = (Node) s.load("org.hibernate.ejb.test.ops.Node", node.getName());
    assertEquals(node.getName(), "foo");
    assertFalse(Hibernate.isInitialized(node));
    tx.commit();
    s.close();

    assertFetchCount(0);
  }
 /**
  * Return the persistent instance of the given entity class with the given identifier, or null if
  * there is no such persistent instance. (If the instance is already associated with the session,
  * return that instance. This method never returns an uninitialized instance.)
  *
  * @param id an identifier
  * @return a persistent instance or null
  * @throws HibernateException Indicates a problem either translating the criteria to SQL,
  *     executing the SQL or processing the SQL results.
  */
 @SuppressWarnings("unchecked")
 public T getById(K id) {
   T result = null;
   Session session = null;
   // get the current session
   session = sessionFactory.getCurrentSession();
   try {
     // perform database access (query, insert, update, etc) here
     try {
       if (id.getClass().getName().startsWith(this.getClass().getPackage().getName())) {
         result = clazz.newInstance();
         result.setId(id);
         result = (T) session.get(clazz, result);
       } else {
         result = (T) session.get(clazz, id);
       }
     } catch (InstantiationException e) {
       result = (T) session.get(clazz, id);
     } catch (IllegalAccessException e) {
       result = (T) session.get(clazz, id);
     }
   } catch (HibernateException e) {
     exceptionHandling(e, session);
   }
   // return result, if needed
   return result;
 }
示例#3
0
文件: OneToMany.java 项目: Hex-s/java
  public static void main(String[] args) {
    Configuration config = new Configuration().configure();
    SessionFactory factory = config.buildSessionFactory();
    Session session = factory.openSession();
    Transaction transaction = session.beginTransaction();
    // 查询第一个老师信息
    Teacher teacher = (Teacher) session.get(Teacher.class, 1);
    // System.out.println(teacher.getTeacherName());
    // 遍历查找该老师所对应的所有学生
    //		for(Student stu : teacher.getStuSet()){
    //			System.out.print("学生姓名:"+stu.getStuName()+",");
    //			System.out.println("任课老师:"+stu.getTeacher().getTeacherName());
    //		}
    Student stu = (Student) session.get(Student.class, 3);
    // 将查到的学生信息添加到老师信息中
    // teacher.getStuSet().add(stu);
    // teacher.getStuSet().remove(stu);
    // 使用inverse将student表的控制权转移给student自身后只能由student对象才能对student表进行数据持久化操作
    // stu.setTeacher(null);

    // 删除老师的信息,配置cascade后可以将学生表和老师表中满足条件的数据都一并删除
    session.delete(teacher);

    transaction.commit();
    session.close();
  }
 public void testSerializableToBlob() throws Exception {
   Book book = new Book();
   Editor editor = new Editor();
   editor.setName("O'Reilly");
   book.setEditor(editor);
   book.setCode2(new char[] {'r'});
   Session s;
   Transaction tx;
   s = openSession();
   tx = s.beginTransaction();
   s.persist(book);
   tx.commit();
   s.close();
   s = openSession();
   tx = s.beginTransaction();
   Book loadedBook = (Book) s.get(Book.class, book.getId());
   assertNotNull(loadedBook.getEditor());
   assertEquals(book.getEditor().getName(), loadedBook.getEditor().getName());
   loadedBook.setEditor(null);
   tx.commit();
   s.close();
   s = openSession();
   tx = s.beginTransaction();
   loadedBook = (Book) s.get(Book.class, book.getId());
   assertNull(loadedBook.getEditor());
   tx.commit();
   s.close();
 }
  public void testUnconstrained() {
    Session session = openSession();
    Transaction tx = session.beginTransaction();
    Person p = new Person("gavin");
    p.setEmployeeId("123456");
    session.persist(p);
    tx.commit();
    session.close();

    session = openSession();
    tx = session.beginTransaction();
    p = (Person) session.get(Person.class, "gavin");
    assertNull(p.getEmployee());
    p.setEmployee(new Employee("123456"));
    tx.commit();
    session.close();

    session = openSession();
    tx = session.beginTransaction();
    p = (Person) session.get(Person.class, "gavin");
    assertTrue(Hibernate.isInitialized(p.getEmployee()));
    assertNotNull(p.getEmployee());
    session.delete(p);
    tx.commit();
    session.close();
  }
  /** The ejb3 find() method maps to the Hibernate get() method */
  public void testGetSemantics() {
    Long nonExistentId = new Long(-1);
    Session s = openSession();
    Transaction txn = s.beginTransaction();
    Item item = (Item) s.get(Item.class, nonExistentId);
    assertNull("get() of non-existent entity did not return null", item);
    txn.commit();
    s.close();

    s = openSession();
    txn = s.beginTransaction();
    // first load() it to generate a proxy...
    item = (Item) s.load(Item.class, nonExistentId);
    assertFalse(Hibernate.isInitialized(item));
    // then try to get() it to make sure we get an exception
    try {
      s.get(Item.class, nonExistentId);
      fail("force load did not fail on non-existent entity");
    } catch (EntityNotFoundException e) {
      // expected behavior
    } catch (AssertionFailedError e) {
      throw e;
    } catch (Throwable t) {
      fail("unexpected exception type on non-existent entity force load : " + t);
    }
    txn.commit();
    s.close();
  }
示例#7
0
  public static void main(String[] args) {
    System.out.println("Hibernate smaple is running");

    Configuration configuration =
        new Configuration().configure(GetDemo.class.getResource("/hibernate.one.to.many.cfg.xml"));
    StandardServiceRegistryBuilder builder =
        new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());

    Session session = sessionFactory.openSession();

    User user = (User) session.get(User.class, 1);
    System.out.println(user);

    User user3 =
        (User)
            session.get(
                User.class,
                10); // 10 is not exist on db BUT not error => IT use load method WILL have
    // exception
    System.out.println(user3);

    sessionFactory.close();

    System.out.println("Hibernate sample stopped");
  }
示例#8
0
  public static Object readRecordByCode(String code, int objectType) {
    // TODO by the candidate
    /*
     * This method is called when you select record in list view of any
     * entity and also called after you save a record to re-bind the record
     * again the code parameter is the first column of the row you have
     * selected and the type is identifier of the object type and may be
     * TYPE_PRODUCT , TYPE_CUSTOMER or TYPE_SALESORDER
     */

    Session session = sessionFactory.getCurrentSession();
    session.beginTransaction();

    Object o = null;
    try {
      switch (objectType) {
        case TYPE_CUSTOMER:
          o = session.get(Customer.class, code);
          break;
        case TYPE_PRODUCT:
          o = session.get(Product.class, code);
          break;
        case TYPE_SALESORDER:
          o = session.get(SalesOrder.class, code);
          break;
        default:
          break;
      }
      session.getTransaction().commit();
    } catch (HibernateException e) {
      logger.error("Error While Retrieving", e);
      session.getTransaction().rollback();
    }
    return o;
  }
  @Test
  public void testInsertGetUpdateGet() {
    Session session = sf.openSession();
    DummyEntity e = new DummyEntity(1L, "test", 0d, null);
    Transaction tx = session.beginTransaction();
    try {
      session.save(e);
      tx.commit();
    } catch (Exception ex) {
      ex.printStackTrace();
      tx.rollback();
      fail(ex.getMessage());
    } finally {
      session.close();
    }

    session = sf.openSession();
    try {
      e = (DummyEntity) session.get(DummyEntity.class, 1L);
      assertEquals("test", e.getName());
      assertNull(e.getDate());
    } catch (Exception ex) {
      ex.printStackTrace();
      fail(ex.getMessage());
    } finally {
      session.close();
    }

    session = sf.openSession();
    tx = session.beginTransaction();
    try {
      e = (DummyEntity) session.get(DummyEntity.class, 1L);
      assertEquals("test", e.getName());
      assertNull(e.getDate());
      e.setName("dummy");
      e.setDate(new Date());
      session.update(e);
      tx.commit();
    } catch (Exception ex) {
      ex.printStackTrace();
      tx.rollback();
      fail(ex.getMessage());
    } finally {
      session.close();
    }

    session = sf.openSession();
    try {
      e = (DummyEntity) session.get(DummyEntity.class, 1L);
      assertEquals("dummy", e.getName());
      Assert.assertNotNull(e.getDate());
    } catch (Exception ex) {
      ex.printStackTrace();
      fail(ex.getMessage());
    } finally {
      session.close();
    }
    //        stats.logSummary();
  }
  @Test
  public void testTopLevelManyToOneChangedToNewEntity() {
    Item item1 = new Item();
    item1.setName("item1 name");
    Category category = new Category();
    category.setName("category");

    item1.setCategory(category);
    category.setExampleItem(item1);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item1);
    tx.commit();
    s.close();

    // get another representation of item1
    s = openSession();
    tx = s.beginTransaction();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    tx.commit();
    s.close();

    // change many-to-one in top level to be a new (transient)
    Category categoryNewer = new Category();
    categoryNewer.setName("newer category");
    item1.setCategory(categoryNewer);

    // put the other representation in categoryNewer
    categoryNewer.setExampleItem(item1_1);

    s = openSession();
    tx = s.beginTransaction();
    Item item1Merged = (Item) s.merge(item1);
    // the many-to-one from the top level item will win.
    assertEquals(categoryNewer.getName(), item1Merged.getCategory().getName());
    assertSame(item1Merged, item1Merged.getCategory().getExampleItem());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    item1 = (Item) s.get(Item.class, item1.getId());
    assertEquals(categoryNewer.getName(), item1.getCategory().getName());
    assertSame(item1, item1.getCategory().getExampleItem());
    // make sure original category is still there
    Category categoryQueried =
        (Category) s.createQuery("from Category c where c.name='category'").uniqueResult();
    assertNotNull(categoryQueried);
    // make sure original category has the same item.
    assertSame(item1, categoryQueried.getExampleItem());
    // set exampleItem to null to avoid constraint violation on cleanup.
    categoryQueried.setExampleItem(null);
    tx.commit();
    s.close();

    cleanup();
  }
  @Test
  public void testBoundedLongByteArrayAccess() {
    byte[] original = buildRecursively(ARRAY_SIZE, true);
    byte[] changed = buildRecursively(ARRAY_SIZE, false);
    byte[] empty = new byte[] {};

    Session s = openSession();
    s.beginTransaction();
    LongByteArrayHolder entity = new LongByteArrayHolder();
    s.save(entity);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    entity = (LongByteArrayHolder) s.get(LongByteArrayHolder.class, entity.getId());
    assertNull(entity.getLongByteArray());
    entity.setLongByteArray(original);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    entity = (LongByteArrayHolder) s.get(LongByteArrayHolder.class, entity.getId());
    Assert.assertEquals(ARRAY_SIZE, entity.getLongByteArray().length);
    assertEquals(original, entity.getLongByteArray());
    entity.setLongByteArray(changed);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    entity = (LongByteArrayHolder) s.get(LongByteArrayHolder.class, entity.getId());
    Assert.assertEquals(ARRAY_SIZE, entity.getLongByteArray().length);
    assertEquals(changed, entity.getLongByteArray());
    entity.setLongByteArray(null);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    entity = (LongByteArrayHolder) s.get(LongByteArrayHolder.class, entity.getId());
    assertNull(entity.getLongByteArray());
    entity.setLongByteArray(empty);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    entity = (LongByteArrayHolder) s.get(LongByteArrayHolder.class, entity.getId());
    if (entity.getLongByteArray() != null) {
      Assert.assertEquals(empty.length, entity.getLongByteArray().length);
      assertEquals(empty, entity.getLongByteArray());
    }
    s.delete(entity);
    s.getTransaction().commit();
    s.close();
  }
  public void execute() {
    Session s = getFactory().openSession();
    s.beginTransaction();

    Entity entity = s.get(Entity.class, entityId);

    Assert.assertFalse(Hibernate.isPropertyInitialized(entity, "description"));
    EnhancerTestUtils.checkDirtyTracking(entity);

    Assert.assertEquals("desc", entity.getDescription());
    Assert.assertTrue(Hibernate.isPropertyInitialized(entity, "description"));

    s.getTransaction().commit();
    s.close();

    s = getFactory().openSession();
    s.beginTransaction();
    entity.setDescription("desc1");
    s.update(entity);

    // Assert.assertFalse( Hibernate.isPropertyInitialized( entity, "description" ) );
    EnhancerTestUtils.checkDirtyTracking(entity, "description");

    Assert.assertEquals("desc1", entity.getDescription());
    Assert.assertTrue(Hibernate.isPropertyInitialized(entity, "description"));

    s.getTransaction().commit();
    s.close();

    s = getFactory().openSession();
    s.beginTransaction();
    entity = s.get(Entity.class, entityId);
    Assert.assertEquals("desc1", entity.getDescription());
    s.getTransaction().commit();
    s.close();

    s = getFactory().openSession();
    s.beginTransaction();
    entity.setDescription("desc2");
    entity = (Entity) s.merge(entity);

    // Assert.assertFalse( Hibernate.isPropertyInitialized( entity, "description" ) );
    EnhancerTestUtils.checkDirtyTracking(entity, "description");

    Assert.assertEquals("desc2", entity.getDescription());
    Assert.assertTrue(Hibernate.isPropertyInitialized(entity, "description"));

    s.getTransaction().commit();
    s.close();

    s = getFactory().openSession();
    s.beginTransaction();
    entity = s.get(Entity.class, entityId);
    Assert.assertEquals("desc2", entity.getDescription());
    s.getTransaction().commit();
    s.close();
  }
  @Test
  @SkipForDialect(value = SybaseASE15Dialect.class, jiraKey = "HHH-6425")
  public void testNewSerializableType() {
    final String initialPayloadText = "Initial payload";
    final String changedPayloadText = "Changed payload";
    final String empty = "";

    Session s = openSession();
    s.beginTransaction();
    SerializableHolder holder = new SerializableHolder();
    s.save(holder);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    holder = (SerializableHolder) s.get(SerializableHolder.class, holder.getId());
    assertNull(holder.getSerialData());
    holder.setSerialData(new SerializableData(initialPayloadText));
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    holder = (SerializableHolder) s.get(SerializableHolder.class, holder.getId());
    SerializableData serialData = (SerializableData) holder.getSerialData();
    assertEquals(initialPayloadText, serialData.getPayload());
    holder.setSerialData(new SerializableData(changedPayloadText));
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    holder = (SerializableHolder) s.get(SerializableHolder.class, holder.getId());
    serialData = (SerializableData) holder.getSerialData();
    assertEquals(changedPayloadText, serialData.getPayload());
    holder.setSerialData(null);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    holder = (SerializableHolder) s.get(SerializableHolder.class, holder.getId());
    assertNull(holder.getSerialData());
    holder.setSerialData(new SerializableData(empty));
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    holder = (SerializableHolder) s.get(SerializableHolder.class, holder.getId());
    serialData = (SerializableData) holder.getSerialData();
    assertEquals(empty, serialData.getPayload());
    s.delete(holder);
    s.getTransaction().commit();
    s.close();
  }
  @Test
  @FailureExpected(jiraKey = "HHH-9239")
  public void testNestedUnidirOneToManyBackrefWithRemovedElement() {
    Item item1 = new Item();
    item1.setName("item1 name");
    SubItem subItem1 = new SubItem();
    subItem1.setName("subItem1 name");
    item1.getSubItemsBackref().add(subItem1);
    SubItem subItem2 = new SubItem();
    subItem2.setName("subItem2 name");
    item1.getSubItemsBackref().add(subItem2);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item1);
    tx.commit();
    s.close();

    // get another representation of item1
    s = openSession();
    tx = s.beginTransaction();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    Hibernate.initialize(item1_1.getSubItemsBackref());
    tx.commit();
    s.close();

    // remove subItem1 from the nested Item
    item1_1.getSubItemsBackref().remove(subItem1);

    Category category = new Category();
    category.setName("category");
    item1.setCategory(category);
    category.setExampleItem(item1_1);

    s = openSession();
    tx = s.beginTransaction();
    Item item1Merged = (Item) s.merge(item1);
    // the element should have been removed
    assertEquals(1, item1Merged.getSubItemsBackref().size());
    assertTrue(item1Merged.getSubItemsBackref().contains(subItem2));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    item1 = (Item) s.get(Item.class, item1.getId());
    assertEquals(1, item1.getSubItemsBackref().size());
    assertTrue(item1.getSubItemsBackref().contains(subItem2));
    // because cascade includes "delete-orphan" the removed SubItem should have been deleted.
    subItem1 = (SubItem) s.get(SubItem.class, subItem1.getId());
    assertNull(subItem1);
    tx.commit();
    s.close();

    cleanup();
  }
示例#15
0
  public void testMapAndElementCollection() throws Exception {
    Session session = openSession();
    Transaction tx = session.beginTransaction();
    Address home = new Address();
    home.setCity("Paris");
    Address work = new Address();
    work.setCity("San Francisco");
    User user = new User();
    user.getAddresses().put("home", home);
    user.getAddresses().put("work", work);
    user.getNicknames().add("idrA");
    user.getNicknames().add("day[9]");
    session.persist(home);
    session.persist(work);
    session.persist(user);
    User user2 = new User();
    user2.getNicknames().add("idrA");
    user2.getNicknames().add("day[9]");
    session.persist(user2);
    tx.commit();

    session.clear();

    tx = session.beginTransaction();
    user = (User) session.get(User.class, user.getId());
    assertThat(user.getNicknames()).as("Should have 2 nick1").hasSize(2);
    assertThat(user.getNicknames()).as("Should contain nicks").contains("idrA", "day[9]");
    user.getNicknames().remove("idrA");
    tx.commit();

    session.clear();

    tx = session.beginTransaction();
    user = (User) session.get(User.class, user.getId());
    // TODO do null value
    assertThat(user.getAddresses()).as("List should have 2 elements").hasSize(2);
    assertThat(user.getAddresses().get("home").getCity())
        .as("home address should be under home")
        .isEqualTo(home.getCity());
    assertThat(user.getNicknames()).as("Should have 1 nick1").hasSize(1);
    assertThat(user.getNicknames()).as("Should contain nick").contains("day[9]");
    session.delete(user);
    session.delete(session.load(Address.class, home.getId()));
    session.delete(session.load(Address.class, work.getId()));

    user2 = (User) session.get(User.class, user2.getId());
    assertThat(user2.getNicknames()).as("Should have 2 nicks").hasSize(2);
    assertThat(user2.getNicknames()).as("Should contain nick").contains("idrA", "day[9]");
    session.delete(user2);

    tx.commit();

    session.close();

    checkCleanCache();
  }
示例#16
0
  @Test
  public void testClear() {

    // clear()方法会清理缓存
    News news1 = (News) session.get(News.class, 1001);
    System.out.println(news1);
    session.clear();
    News news2 = (News) session.get(News.class, 1001);
    System.out.println(news2);
  }
  @Test
  // @FailureExpected( jiraKey = "HHH-9106" )
  public void testTopLevelUnidirOneToManyBackrefWithRemovedElement() {
    Item item1 = new Item();
    item1.setName("item1 name");
    SubItem subItem1 = new SubItem();
    subItem1.setName("subItem1 name");
    item1.getSubItemsBackref().add(subItem1);
    SubItem subItem2 = new SubItem();
    subItem2.setName("subItem2 name");
    item1.getSubItemsBackref().add(subItem2);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item1);
    tx.commit();
    s.close();

    // get another representation of item1
    s = openSession();
    tx = s.beginTransaction();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    tx.commit();
    s.close();

    assertFalse(Hibernate.isInitialized(item1_1.getSubItemsBackref()));

    Category category = new Category();
    category.setName("category");

    item1.setCategory(category);
    category.setExampleItem(item1_1);

    // remove subItem1 from top-level Item
    item1.getSubItemsBackref().remove(subItem1);

    s = openSession();
    tx = s.beginTransaction();
    Item item1Merged = (Item) s.merge(item1);
    // entity should have been removed
    assertEquals(1, item1Merged.getSubItemsBackref().size());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    item1 = (Item) s.get(Item.class, item1.getId());
    assertEquals(1, item1.getSubItemsBackref().size());
    subItem1 = (SubItem) s.get(SubItem.class, subItem1.getId());
    // cascade does not include delete-orphan, so subItem1 should still be persistent.
    assertNotNull(subItem1);
    tx.commit();

    cleanup();
  }
  @Test
  @FailureExpected(jiraKey = "HHH-9239")
  public void testNestedUnidirOneToManyBackrefWithNewElement() {
    Item item1 = new Item();
    item1.setName("item1 name");
    SubItem subItem1 = new SubItem();
    subItem1.setName("subItem1 name");
    item1.getSubItemsBackref().add(subItem1);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item1);
    tx.commit();
    s.close();

    // get another representation of item1
    s = openSession();
    tx = s.beginTransaction();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    Hibernate.initialize(item1_1.getSubItemsBackref());
    tx.commit();
    s.close();

    Category category = new Category();
    category.setName("category");
    item1.setCategory(category);

    // Add a new SubItem to the Item representation that will be in a nested association.
    SubItem subItem2 = new SubItem();
    subItem2.setName("subItem2 name");
    item1_1.getSubItemsBackref().add(subItem2);

    category.setExampleItem(item1_1);

    s = openSession();
    tx = s.beginTransaction();
    Item item1Merged = (Item) s.merge(item1);
    // The resulting collection should contain the added element
    assertEquals(2, item1Merged.getSubItemsBackref().size());
    assertEquals("subItem1 name", item1Merged.getSubItemsBackref().get(0).getName());
    assertEquals("subItem2 name", item1Merged.getSubItemsBackref().get(1).getName());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    item1 = (Item) s.get(Item.class, item1.getId());
    assertEquals(2, item1.getSubItemsBackref().size());
    assertEquals("subItem1 name", item1.getSubItemsBackref().get(0).getName());
    assertEquals("subItem2 name", item1.getSubItemsBackref().get(1).getName());
    tx.commit();
    s.close();

    cleanup();
  }
  @Test
  // @FailureExpected( jiraKey = "HHH-9106" )
  public void testTopLevelUnidirOneToManyNoBackrefWithRemovedElement() {
    Category category1 = new Category();
    category1.setName("category1 name");
    SubCategory subCategory1 = new SubCategory();
    subCategory1.setName("subCategory1 name");
    category1.getSubCategories().add(subCategory1);
    SubCategory subCategory2 = new SubCategory();
    subCategory2.setName("subCategory2 name");
    category1.getSubCategories().add(subCategory2);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(category1);
    tx.commit();
    s.close();

    // get another representation of category1
    s = openSession();
    tx = s.beginTransaction();
    Category category1_1 = (Category) s.get(Category.class, category1.getId());
    tx.commit();
    s.close();

    assertFalse(Hibernate.isInitialized(category1_1.getSubCategories()));

    Item item = new Item();
    item.setName("item");
    category1.setExampleItem(item);
    item.setCategory(category1_1);

    category1.getSubCategories().remove(subCategory1);

    s = openSession();
    tx = s.beginTransaction();
    Category category1Merged = (Category) s.merge(category1);
    assertEquals(1, category1Merged.getSubCategories().size());
    assertTrue(category1Merged.getSubCategories().contains(subCategory2));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    category1 = (Category) s.get(Category.class, category1.getId());
    assertEquals(1, category1.getSubCategories().size());
    assertTrue(category1.getSubCategories().contains(subCategory2));
    // cascade does not include delete-orphan, so subCategory1 should still be persistent.
    subCategory1 = (SubCategory) s.get(SubCategory.class, subCategory1.getId());
    assertNotNull(subCategory1);
    tx.commit();
    s.close();

    cleanup();
  }
示例#20
0
 @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
 public boolean removeUser(@PathVariable Long id) {
   User u = session.get(User.class, id);
   if (u != null) {
     session.delete(u);
     session.flush();
     System.out.println("Deleted user: " + u.getId());
     return session.get(User.class, id) == null;
   }
   return false;
 }
  public void XtestDuplicateDeleteExecuteBulk() throws Exception {
    session.save(new Simple(1, "test"));
    assertNotNull(session.get(Simple.class, 1));

    List<BulkItem> bulkItems = new ArrayList<BulkItem>();
    bulkItems.add(new MockBulkItem(new Simple(1, "test"), BulkItem.REMOVE));
    bulkItems.add(new MockBulkItem(new Simple(1, "test"), BulkItem.REMOVE));
    bulkDataPersister.executeBulk(bulkItems);

    assertNull(session.get(Simple.class, 2));
  }
  @Test
  @FailureExpected(jiraKey = "HHH-9240")
  public void testTopLevelUnidirOneToManyBackrefWithNewElement() {
    Item item1 = new Item();
    item1.setName("item1 name");
    SubItem subItem1 = new SubItem();
    subItem1.setName("subItem1 name");
    item1.getSubItemsBackref().add(subItem1);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item1);
    tx.commit();
    s.close();

    // get another representation of item1
    s = openSession();
    tx = s.beginTransaction();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    tx.commit();
    s.close();

    assertFalse(Hibernate.isInitialized(item1_1.getSubItemsBackref()));

    Category category = new Category();
    category.setName("category");

    SubItem subItem2 = new SubItem();
    subItem2.setName("subItem2 name");
    item1.getSubItemsBackref().add(subItem2);

    item1.setCategory(category);
    category.setExampleItem(item1_1);

    s = openSession();
    tx = s.beginTransaction();
    // The following will fail due to PropertyValueException because item1  will
    // be removed from the inverted merge map when the operation cascades to item1_1.
    Item item1Merged = (Item) s.merge(item1);
    // top-level collection should win
    assertEquals(2, item1.getSubItemsBackref().size());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    item1 = (Item) s.get(Item.class, item1.getId());
    assertEquals(2, item1.getSubItemsBackref().size());
    tx.commit();
    s.close();

    cleanup();
  }
示例#23
0
 @Test
 public void testClear() {
   Session session = sf.openSession();
   Transaction tx = session.beginTransaction();
   User user = null;
   user = (User) session.get(User.class, 2);
   // session.clear();//清空所有,会使user指向的对象变为游离状态
   session.evict(user); // 清除指定对象,会使user指向的对象变为游离状态
   user = (User) session.get(User.class, 2); // 会再次执行一次查询语句
   tx.commit(); // 该方法会调用flush
   session.close();
 }
  @Test
  @FailureExpected(jiraKey = "HHH-9239")
  public void testNestedUnidirOneToManyNoBackrefWithRemovedElement() {
    Category category1 = new Category();
    category1.setName("category1 name");
    SubCategory subCategory1 = new SubCategory();
    subCategory1.setName("subCategory1 name");
    category1.getSubCategories().add(subCategory1);
    SubCategory subCategory2 = new SubCategory();
    subCategory2.setName("subCategory2 name");
    category1.getSubCategories().add(subCategory2);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(category1);
    tx.commit();
    s.close();

    // get another representation of category1
    s = openSession();
    tx = s.beginTransaction();
    Category category1_1 = (Category) s.get(Category.class, category1.getId());
    Hibernate.initialize(category1_1.getSubCategories());
    tx.commit();
    s.close();

    category1_1.getSubCategories().remove(subCategory2);

    Item item = new Item();
    item.setName("item");
    category1.setExampleItem(item);
    item.setCategory(category1_1);

    s = openSession();
    tx = s.beginTransaction();
    Category category1Merged = (Category) s.merge(category1);
    assertEquals(1, category1Merged.getSubCategories().size());
    assertTrue(category1Merged.getSubCategories().contains(subCategory2));
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    category1 = (Category) s.get(Category.class, category1.getId());
    assertEquals(1, category1.getSubCategories().size());
    assertTrue(category1.getSubCategories().contains(subCategory2));
    subCategory1 = (SubCategory) s.get(SubCategory.class, subCategory1.getId());
    assertNull(subCategory1);
    tx.commit();
    s.close();

    cleanup();
  }
  @Test
  public void testNestedManyToOneChangedToNewEntity() {
    Item item1 = new Item();
    item1.setName("item1 name");
    Category category = new Category();
    category.setName("category");

    item1.setCategory(category);
    category.setExampleItem(item1);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item1);
    tx.commit();
    s.close();

    // get another representation of item1
    s = openSession();
    tx = s.beginTransaction();
    Item item1_1 = (Item) s.get(Item.class, item1.getId());
    tx.commit();
    s.close();

    // change many-to-one in nested entity to a new (transient) value
    Category categoryNew = new Category();
    categoryNew.setName("new category");
    item1_1.setCategory(categoryNew);
    item1.getCategory().setExampleItem(item1_1);

    s = openSession();
    tx = s.beginTransaction();
    Item item1Merged = (Item) s.merge(item1);
    // the many-to-one from the top level item will win.
    assertEquals(category.getName(), item1Merged.getCategory().getName());
    assertSame(item1Merged, item1Merged.getCategory().getExampleItem());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    item1 = (Item) s.get(Item.class, item1.getId());
    assertEquals(category.getName(), item1.getCategory().getName());
    assertSame(item1, item1.getCategory().getExampleItem());
    // make sure new category got persisted
    Category categoryQueried =
        (Category) s.createQuery("from Category c where c.name='new category'").uniqueResult();
    assertNotNull(categoryQueried);
    tx.commit();
    s.close();

    cleanup();
  }
  public void testIndexFormulaMap() {
    Session s = openSession();
    Transaction t = s.beginTransaction();
    User gavin = new User("gavin", "secret");
    User turin = new User("turin", "tiger");
    Group g = new Group("developers");
    g.getUsers().put("gavin", gavin);
    g.getUsers().put("turin", turin);
    s.persist(g);
    gavin.getSession().put("foo", new SessionAttribute("foo", "foo bar baz"));
    gavin.getSession().put("bar", new SessionAttribute("bar", "foo bar baz 2"));
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    g = (Group) s.get(Group.class, "developers");
    assertEquals(g.getUsers().size(), 2);
    g.getUsers().remove("turin");
    Map smap = ((User) g.getUsers().get("gavin")).getSession();
    assertEquals(smap.size(), 2);
    smap.remove("bar");
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    g = (Group) s.get(Group.class, "developers");
    assertEquals(g.getUsers().size(), 1);
    smap = ((User) g.getUsers().get("gavin")).getSession();
    assertEquals(smap.size(), 1);
    gavin = (User) g.getUsers().put("gavin", turin);
    s.delete(gavin);
    assertEquals(
        s.createQuery("select count(*) from SessionAttribute").uniqueResult(), new Integer(0));
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    g = (Group) s.get(Group.class, "developers");
    assertEquals(g.getUsers().size(), 1);
    turin = (User) g.getUsers().get("turin");
    smap = turin.getSession();
    assertEquals(smap.size(), 0);
    assertEquals(s.createQuery("select count(*) from User").uniqueResult(), new Integer(1));
    s.delete(g);
    s.delete(turin);
    assertEquals(s.createQuery("select count(*) from User").uniqueResult(), new Integer(0));
    t.commit();
    s.close();
  }
  @Test
  public void testTopLevelEntityNewerThanNested() {
    Item item = new Item();
    item.setName("item");

    Category category = new Category();
    category.setName("category");

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(item);
    s.persist(category);
    tx.commit();
    s.close();

    // Get the Category from a different session.
    s = openSession();
    tx = s.beginTransaction();
    Category category1_2 = (Category) s.get(Category.class, category.getId());
    tx.commit();
    s.close();

    // Get and update the same Category.
    s = openSession();
    tx = s.beginTransaction();
    Category category1_1 = (Category) s.get(Category.class, category.getId());
    category1_1.setName("new name");
    tx.commit();
    s.close();

    assertTrue(category1_2.getVersion() < category1_1.getVersion());

    category1_1.setExampleItem(item);
    item.setCategory(category1_2);

    s = openSession();
    tx = s.beginTransaction();
    try {
      // representation merged at top level is newer than nested representation.
      category1_1 = (Category) s.merge(category1_1);
      fail("should have failed because one representation is an older version.");
    } catch (StaleObjectStateException ex) {
      // expected
    } finally {
      tx.rollback();
      s.close();
    }

    cleanup();
  }
  @Test
  // @FailureExpected( jiraKey = "HHH-9106" )
  public void testTopLevelUnidirOneToManyNoBackrefWithNewElement() {
    Category category1 = new Category();
    category1.setName("category1 name");
    SubCategory subCategory1 = new SubCategory();
    subCategory1.setName("subCategory1 name");
    category1.getSubCategories().add(subCategory1);

    Session s = openSession();
    Transaction tx = s.beginTransaction();
    s.persist(category1);
    tx.commit();
    s.close();

    // get another representation of category1
    s = openSession();
    tx = s.beginTransaction();
    Category category1_1 = (Category) s.get(Category.class, category1.getId());
    tx.commit();
    s.close();

    assertFalse(Hibernate.isInitialized(category1_1.getSubCategories()));

    SubCategory subCategory2 = new SubCategory();
    subCategory2.setName("subCategory2 name");
    category1.getSubCategories().add(subCategory2);

    Item item = new Item();
    item.setName("item");
    category1.setExampleItem(item);
    item.setCategory(category1_1);

    s = openSession();
    tx = s.beginTransaction();
    Category category1Merged = (Category) s.merge(category1);
    assertEquals(2, category1Merged.getSubCategories().size());
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    category1 = (Category) s.get(Category.class, category1.getId());
    assertEquals(2, category1.getSubCategories().size());
    tx.commit();
    s.close();

    cleanup();
  }
示例#29
0
  /**
   * Test the equivalent of EJB3 LockModeType.READ
   *
   * <p>From the spec:
   *
   * <p>If transaction T1 calls lock(entity, LockModeType.READ) on a versioned object, the entity
   * manager must ensure that neither of the following phenomena can occur:
   *
   * <ul>
   *   <li>P1 (Dirty read): Transaction T1 modifies a row. Another transaction T2 then reads that
   *       row and obtains the modified value, before T1 has committed or rolled back. Transaction
   *       T2 eventually commits successfully; it does not matter whether T1 commits or rolls back
   *       and whether it does so before or after T2 commits.
   *   <li>P2 (Non-repeatable read): Transaction T1 reads a row. Another transaction T2 then
   *       modifies or deletes that row, before T1 has committed. Both transactions eventually
   *       commit successfully.
   *       <p>This will generally be achieved by the entity manager acquiring a lock on the
   *       underlying database row. Any such lock may be obtained immediately (so long as it is
   *       retained until commit completes), or the lock may be deferred until commit time (although
   *       even then it must be retained until the commit completes). Any implementation that
   *       supports repeatable reads in a way that prevents the above phenomena is permissible.
   *       <p>The persistence implementation is not required to support calling lock(entity,
   *       LockMode-Type.READ) on a non-versioned object. When it cannot support such a lock call,
   *       it must throw the PersistenceException. When supported, whether for versioned or
   *       non-versioned objects, LockMode-Type.READ must always prevent the phenomena P1 and P2.
   *       Applications that call lock(entity, LockModeType.READ) on non-versioned objects will not
   *       be portable.
   *       <p>Odd as it may sound, EJB3 LockModeType.READ actually maps to the Hibernate
   *       LockMode.UPGRADE
   */
  public void testLockModeTypeRead() {
    if (!readCommittedIsolationMaintained("ejb3 lock tests")) {
      return;
    }
    if (getDialect().doesReadCommittedCauseWritersToBlockReaders()) {
      reportSkip("deadlock", "jpa read locking");
      return;
    }

    final String initialName = "lock test";
    // set up some test data
    Session s1 = getSessions().openSession();
    Transaction t1 = s1.beginTransaction();
    Item item = new Item();
    item.setName(initialName);
    s1.save(item);
    t1.commit();
    s1.close();

    Long itemId = item.getId();

    // perform the isolated update
    s1 = getSessions().openSession();
    t1 = s1.beginTransaction();
    item = (Item) s1.get(Item.class, itemId);
    s1.lock(item, LockMode.UPGRADE);
    item.setName("updated");
    s1.flush();

    Session s2 = getSessions().openSession();
    Transaction t2 = s2.beginTransaction();
    Item item2 = (Item) s2.get(Item.class, itemId);
    assertEquals("isolation not maintained", initialName, item2.getName());

    t1.commit();
    s1.close();

    item2 = (Item) s2.get(Item.class, itemId);
    assertEquals("repeatable read not maintained", initialName, item2.getName());
    t2.commit();
    s2.close();

    s1 = getSessions().openSession();
    t1 = s1.beginTransaction();
    s1.delete(item);
    t1.commit();
    s1.close();
  }
  @Test
  public void testNative() throws Exception {
    final ServiceReference sr = bundleContext.getServiceReference(SessionFactory.class.getName());
    final SessionFactory sf = (SessionFactory) bundleContext.getService(sr);

    Session s = sf.openSession();
    s.getTransaction().begin();
    s.persist(new DataPoint("Brett"));
    s.getTransaction().commit();
    s.close();

    s = sf.openSession();
    s.getTransaction().begin();
    DataPoint dp = (DataPoint) s.get(DataPoint.class, 1);
    assertNotNull(dp);
    assertEquals("Brett", dp.getName());
    s.getTransaction().commit();
    s.close();

    dp.setName("Brett2");

    s = sf.openSession();
    s.getTransaction().begin();
    s.update(dp);
    s.getTransaction().commit();
    s.close();

    s = sf.openSession();
    s.getTransaction().begin();
    dp = (DataPoint) s.get(DataPoint.class, 1);
    assertNotNull(dp);
    assertEquals("Brett2", dp.getName());
    s.getTransaction().commit();
    s.close();

    s = sf.openSession();
    s.getTransaction().begin();
    s.createQuery("delete from DataPoint").executeUpdate();
    s.getTransaction().commit();
    s.close();

    s = sf.openSession();
    s.getTransaction().begin();
    dp = (DataPoint) s.get(DataPoint.class, 1);
    assertNull(dp);
    s.getTransaction().commit();
    s.close();
  }