@Override
  public ArrayList<User> getAllUsers() throws Exception {
    dLog.info("Entering method getAllUsers");
    ArrayList<User> result = new ArrayList<User>();
    Session session = null;

    try {
      session = getSession();
      session.clear();
      Transaction tranx = session.beginTransaction();

      String hql = "select from User";
      Query query = session.createQuery(hql);
      List<?> list = query.list();

      for (int n = 0; n < list.size(); n++) {
        result.add((User) list.get(n));
      }

      tranx.commit();
      session.flush();
      session.evict(User.class);
    } catch (Exception e) {
      dLog.error("Exception in getAllUsers", e);
    } finally {
      // ensure that session is close regardless of the errors in try/catch
      if (session != null) {
        session.close();
      }
    }

    return result;
  }
  @Override
  public void getPortalEvents(
      DateTime startTime,
      DateTime endTime,
      int maxEvents,
      FunctionWithoutResult<PortalEvent> handler) {
    final Session session = this.getEntityManager().unwrap(Session.class);
    final org.hibernate.Query query = session.createQuery(this.selectQuery);
    query.setParameter(this.startTimeParameter.getName(), startTime);
    query.setParameter(this.endTimeParameter.getName(), endTime);
    if (maxEvents > 0) {
      query.setMaxResults(maxEvents);
    }

    for (final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
        results.next(); ) {
      final PersistentPortalEvent persistentPortalEvent = (PersistentPortalEvent) results.get(0);
      final PortalEvent portalEvent =
          this.toPortalEvent(
              persistentPortalEvent.getEventData(), persistentPortalEvent.getEventType());
      handler.apply(portalEvent);
      persistentPortalEvent.setAggregated(true);
      session.evict(persistentPortalEvent);
    }
  }
  @Test
  public void testLoadBoardImpl() throws BoardLoadingException {
    final ScribbleSettings settings = new ScribbleSettings("Mock", Language.EN, 3);

    final Dictionary dictionary = createNiceMock(Dictionary.class);
    final TilesBank tilesBank =
        new TilesBank(new TilesBankInfoEditor(Language.EN).createTilesBankInfo());

    final ScribbleBoard board = createStrictMock(ScribbleBoard.class);
    expect(board.getSettings()).andReturn(settings);
    expect(board.getPlayersCount()).andReturn(3);
    board.initGameAfterLoading(tilesBank, dictionary, personalityManager);
    replay(board);

    expect(session.get(ScribbleBoard.class, 1L)).andReturn(board);
    session.evict(board);
    replay(session);

    expect(dictionaryManager.getDictionary(Language.EN)).andReturn(dictionary);
    replay(dictionaryManager);

    expect(tilesBankingHouse.createTilesBank(Language.EN, 3, true)).andReturn(tilesBank);
    replay(tilesBankingHouse);

    final ScribbleBoard board1 = scribblePlayManager.loadBoardImpl(1L);
    assertSame(board, board1);

    verify(board);
    verify(session);
    verify(dictionaryManager);
    verify(tilesBankingHouse);
  }
Beispiel #4
0
  public void insertDetail(OrdDetailBean detailBean) {
    session.save(detailBean);

    session.evict(detailBean);

    System.out.println(detailBean);
  }
  @Test
  @SuppressWarnings({"unchecked"})
  public void testIterateWithEvictBottomOfLoop() {
    Session s = openSession();
    s.beginTransaction();
    Set parents = new HashSet();
    for (int i = 0; i < 5; i++) {
      Parent p = new Parent(String.valueOf(i + 100));
      Child child = new Child("child" + i);
      child.setParent(p);
      p.getChildren().add(child);
      s.save(p);
      parents.add(p);
    }
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    for (Iterator it = s.createQuery("from Parent").iterate(); it.hasNext(); ) {
      Parent p = (Parent) it.next();
      assertEquals(1, p.getChildren().size());
      s.evict(p);
    }
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    for (Object parent : parents) {
      s.delete(parent);
    }
    s.getTransaction().commit();
    s.close();
  }
  @Test
  public void testUpdateAfterEvict() {
    Session s = openSession();
    s.beginTransaction();
    Parent p = new Parent("p");
    s.save(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    p = (Parent) s.load(Parent.class, "p");
    // evict...
    s.evict(p);
    // now try to reattach...
    s.update(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    s.delete(p);
    s.getTransaction().commit();
    s.close();
  }
  @SuppressWarnings("unchecked")
  @Override
  protected void handle(TitoRequest req, Session hs, TemplateRenderer tr, ViewResponse resp)
      throws ErrorResponseException {
    User user = req.getUserSession().consumeAttribute("regUser", User.class);
    if (user == null) user = new User();

    tr.put("theUser", user); // Use "theUser" instead of "user" to avoid name clash
    tr.put("availableLocales", req.getContext().getTitoTranslation().getSupportedLocales());

    final Locale locale = this.getTranslator(req).getLocale();
    List<Course> courses = hs.createQuery("FROM Course WHERE hidden = FALSE").list();
    hs.evict(courses);
    Collections.sort(
        courses,
        new Comparator<Course>() {
          @Override
          public int compare(Course o1, Course o2) {
            String s1 = ObjectUtils.toString(o1.getName(locale), "");
            String s2 = ObjectUtils.toString(o2.getName(locale), "");
            return s1.compareTo(s2);
          }
        });

    tr.put("availableCourses", courses);

    tr.put("invFields", req.getUserSession().consumeAttribute("invFields", Collection.class));
  }
  public void testUpdateOwnerAfterEvict() {
    Session s = openSession();
    s.beginTransaction();
    Parent p = new Parent("p");
    p.getChildren().add(new Child("c"));
    s.save(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    p = (Parent) s.get(Parent.class, "p");
    // evict...
    s.evict(p);
    // now try to reattach...
    s.update(p);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();
    s.delete(p);
    s.getTransaction().commit();
    s.close();
  }
Beispiel #9
0
  public void delete(Countries countries) {

    Transaction transaction = session.beginTransaction();
    transaction.begin();
    session.evict(countries);
    session.delete(countries);
    transaction.commit();
  }
  @Test
  public void create() {
    final PublicMessage pm = getPublicMessage(1).get(0);
    publicMessageDao.save(pm);
    session.evict(pm);

    assertEquals(session.get(PublicMessage.class, pm.getId()), pm);
  }
  @Test
  public void deleteByObject() {
    final PublicMessage pm = getPublicMessage(1).get(0);
    session.save(pm);
    session.evict(pm);

    publicMessageDao.delete(pm);
    assertNull(session.get(PublicMessage.class, pm.getId()));
  }
  @Test
  public void testEntity() {
    final HazelcastInstance hz = getHazelcastInstance(sf);
    assertNotNull(hz);
    final int count = 100;
    final int childCount = 3;
    insertDummyEntities(count, childCount);
    List<DummyEntity> list = new ArrayList<DummyEntity>(count);
    Session session = sf.openSession();
    try {
      for (int i = 0; i < count; i++) {
        DummyEntity e = (DummyEntity) session.get(DummyEntity.class, (long) i);
        session.evict(e);
        list.add(e);
      }
    } finally {
      session.close();
    }
    session = sf.openSession();
    Transaction tx = session.beginTransaction();
    try {
      for (DummyEntity dummy : list) {
        dummy.setDate(new Date());
        session.update(dummy);
      }
      tx.commit();
    } catch (Exception e) {
      tx.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }

    Statistics stats = sf.getStatistics();
    Map<?, ?> cache = hz.getMap(DummyEntity.class.getName());
    Map<?, ?> propCache = hz.getMap(DummyProperty.class.getName());
    Map<?, ?> propCollCache = hz.getMap(DummyEntity.class.getName() + ".properties");
    assertEquals((childCount + 1) * count, stats.getEntityInsertCount());
    // twice put of entity and properties (on load and update) and once put of collection
    // TODO: fix next assertion ->
    //        assertEquals((childCount + 1) * count * 2, stats.getSecondLevelCachePutCount());
    assertEquals(childCount * count, stats.getEntityLoadCount());
    assertEquals(count, stats.getSecondLevelCacheHitCount());
    // collection cache miss
    assertEquals(count, stats.getSecondLevelCacheMissCount());
    assertEquals(count, cache.size());
    assertEquals(count * childCount, propCache.size());
    assertEquals(count, propCollCache.size());
    sf.getCache().evictEntityRegion(DummyEntity.class);
    sf.getCache().evictEntityRegion(DummyProperty.class);
    assertEquals(0, cache.size());
    assertEquals(0, propCache.size());
    stats.logSummary();
  }
Beispiel #13
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();
 }
 protected ArrayList<DummyEntity> getDummyEntities(SessionFactory sf, long untilId) {
   Session session = sf.openSession();
   ArrayList<DummyEntity> entities = new ArrayList<DummyEntity>();
   for (long i = 0; i < untilId; i++) {
     DummyEntity entity = (DummyEntity) session.get(DummyEntity.class, i);
     if (entity != null) {
       session.evict(entity);
       entities.add(entity);
     }
   }
   session.close();
   return entities;
 }
Beispiel #15
0
	@SuppressWarnings("unchecked")
	public static void main(String[] args){
		Session session = Hibernate.currentSession();//Open a session which is created by the SessionFactory
		Transaction tx = session.beginTransaction();//transaction starts
		User user = new User("Tommy", 50);//transient status
		session.save(user);//insertion
		tx.commit();//transaction ends
		session.evict(user);
		String hql = "from User";//select * from User
		Query query = session.createQuery(hql);
		System.out.println(************************);
		List<User> list = query.list();//it returns a list of objects
		for(User u:list){
			System.out.println(u);
			System.out.println("user==u?" + (user==u));
		}
		Hibernate,closeSession();//After manipulation, it needs to close
	}
  @Test
  public void testSaveBoardImpl() {
    final ScribbleBoard board = createNiceMock(ScribbleBoard.class);

    session.saveOrUpdate(board);
    session.flush();
    session.evict(board);
    replay(session);

    replay(dictionaryManager);
    replay(tilesBankingHouse);

    scribblePlayManager.saveBoardImpl(board);

    verify(session);
    verify(dictionaryManager);
    verify(tilesBankingHouse);
  }
 protected void executeUpdateQuery(SessionFactory sf, String queryString) throws RuntimeException {
   Session session = null;
   Transaction txn = null;
   try {
     session = sf.openSession();
     txn = session.beginTransaction();
     Query query = session.createQuery(queryString);
     query.setCacheable(true);
     session.evict(query);
     query.executeUpdate();
     txn.commit();
   } catch (RuntimeException e) {
     txn.rollback();
     e.printStackTrace();
     throw e;
   } finally {
     session.close();
   }
 }
Beispiel #18
0
  @Test
  public void save() {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();

    User user = new User();
    session.save(user);
    session.flush();
    session.evict(user);

    user = (User) session.get(User.class, user.getId());

    System.out.println(user.getTs());
    System.out.println(user.getTs2());
    System.out.println(user.getCal());

    tx.commit();
    session.close();
  }
  @Test
  @SuppressWarnings({"UnusedAssignment"})
  public void testEvictThenSaveOrUpdate() throws Exception {
    TestingJtaBootstrap.INSTANCE.getTransactionManager().begin();
    Session s = openSession();
    Node parent = new Node("1:parent");
    Node child = new Node("2:child");
    Node grandchild = new Node("3:grandchild");
    parent.addChild(child);
    child.addChild(grandchild);
    s.saveOrUpdate(parent);
    s = applyNonFlushedChangesToNewSessionCloseOldSession(s);
    TestingJtaBootstrap.INSTANCE.getTransactionManager().commit();

    TestingJtaBootstrap.INSTANCE.getTransactionManager().begin();
    Session s1 = openSession();
    child = (Node) s1.load(Node.class, "2:child");
    s1 = applyNonFlushedChangesToNewSessionCloseOldSession(s1);
    child = (Node) getOldToNewEntityRefMap().get(child);
    assertTrue(s1.contains(child));
    assertFalse(Hibernate.isInitialized(child));
    assertTrue(s1.contains(child.getParent()));
    assertTrue(Hibernate.isInitialized(child));
    assertFalse(Hibernate.isInitialized(child.getChildren()));
    assertFalse(Hibernate.isInitialized(child.getParent()));
    assertTrue(s1.contains(child));
    s1 = applyNonFlushedChangesToNewSessionCloseOldSession(s1);
    // child is an initialized proxy; after serialization, it is
    // the proxy is replaced by its implementation
    // TODO: find out if this is how this should work...
    child =
        (Node)
            getOldToNewEntityRefMap()
                .get(((HibernateProxy) child).getHibernateLazyInitializer().getImplementation());
    s1.evict(child);
    assertFalse(s1.contains(child));
    assertTrue(s1.contains(child.getParent()));

    javax.transaction.Transaction tx1 =
        TestingJtaBootstrap.INSTANCE.getTransactionManager().suspend();

    TestingJtaBootstrap.INSTANCE.getTransactionManager().begin();
    Session s2 = openSession();
    try {
      s2.getTransaction().begin();
      s2.saveOrUpdate(child);
      fail();
    } catch (HibernateException ex) {
      // expected because parent is connected to s1
    } finally {
      TestingJtaBootstrap.INSTANCE.getTransactionManager().rollback();
    }

    s1.evict(child.getParent());
    assertFalse(s1.contains(child.getParent()));

    TestingJtaBootstrap.INSTANCE.getTransactionManager().begin();
    s2 = openSession();
    s2.saveOrUpdate(child);
    s2 = applyNonFlushedChangesToNewSessionCloseOldSession(s2);
    child = (Node) getOldToNewEntityRefMap().get(child);
    assertTrue(s2.contains(child));
    assertFalse(s1.contains(child));
    assertTrue(s2.contains(child.getParent()));
    assertFalse(s1.contains(child.getParent()));
    assertFalse(Hibernate.isInitialized(child.getChildren()));
    assertFalse(Hibernate.isInitialized(child.getParent()));
    assertEquals(1, child.getChildren().size());
    assertEquals("1:parent", child.getParent().getName());
    assertTrue(Hibernate.isInitialized(child.getChildren()));
    assertFalse(Hibernate.isInitialized(child.getParent()));
    assertNull(child.getParent().getDescription());
    assertTrue(Hibernate.isInitialized(child.getParent()));
    s1 = applyNonFlushedChangesToNewSessionCloseOldSession(s1);
    s2 = applyNonFlushedChangesToNewSessionCloseOldSession(s2);
    TestingJtaBootstrap.INSTANCE.getTransactionManager().commit();

    TestingJtaBootstrap.INSTANCE.getTransactionManager().resume(tx1);
    TestingJtaBootstrap.INSTANCE.getTransactionManager().commit();
    //		tx1.commit();

    TestingJtaBootstrap.INSTANCE.getTransactionManager().begin();
    s = openSession();
    s.delete(s.get(Node.class, "3:grandchild"));
    s.delete(s.get(Node.class, "2:child"));
    s.delete(s.get(Node.class, "1:parent"));
    TestingJtaBootstrap.INSTANCE.getTransactionManager().commit();
  }
Beispiel #20
0
 public void evict(Object object) throws HibernateException {
   session.evict(object);
 }