public Object execute(Environment environment) throws Exception {
    Session session = environment.get(Session.class);

    Query query =
        session.createQuery(
            "select distinct hai.activityName "
                + "from "
                + HistoryActivityInstanceImpl.class.getName()
                + " as hai "
                + "where hai.historyProcessInstance.processDefinitionId = :processDefinitionId");
    query.setString("processDefinitionId", processDefinitionId);

    Map<String, Long> avgDuration = new HashMap<String, Long>();

    List<String> activityNames = query.list();
    for (String activityName : activityNames) {
      query =
          session.createQuery(
              "select avg(hai.duration) "
                  + "from "
                  + HistoryActivityInstanceImpl.class.getName()
                  + " as hai "
                  + "where hai.historyProcessInstance.processDefinitionId = :processDefinitionId "
                  + "  and hai.activityName = :activityName");
      query.setString("processDefinitionId", processDefinitionId);
      query.setString("activityName", activityName);

      Number number = (Number) query.uniqueResult();
      avgDuration.put(activityName, new Long(number.longValue()));
    }

    return avgDuration;
  }
Exemplo n.º 2
0
  public int getCountOfSubscribers(int forumId, int userId) {
    // TODO Auto-generated method stub
    Session session = this.sessionFactory.openSession();
    Transaction tx = null;
    int countOfSubscribers = 0;
    try {
      tx = session.beginTransaction();
      Query query = null;
      if (userId == 0) {
        query = session.createQuery("select count(*) from Subscription where forumId = :forumId");
        query.setParameter("forumId", forumId);
      } else {
        query =
            session.createQuery(
                "select count(*) from Subscription where forumId = :forumId and userId = :userId");
        query.setParameter("forumId", forumId);
        query.setParameter("userId", userId);
      }

      Long count = (Long) query.uniqueResult();
      countOfSubscribers = count.intValue();
      // System.out.println("No of subscribers.."+countOfSubscribers);
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return countOfSubscribers;
  }
Exemplo n.º 3
0
 public List<User> getUserSearchResults(int topicId) {
   // TODO Auto-generated method stub
   List<User> userArr = new ArrayList<User>();
   Session session = sessionFactory.openSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Query query1 = session.createQuery("select userId from UserTopic where topicId = :topicId");
     query1.setString("topicId", String.valueOf(topicId));
     Query query2 = session.createQuery("from User where userId in (:userList)");
     query2.setParameterList("userList", query1.list());
     userArr = query2.list();
     /*for(Topic topic : topicArr){
     	System.out.println("Topic Description----"+topic.getTopicDescription());
     	System.out.println("Topic Id----"+topic.getTopicId());
     }*/
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
   return userArr;
 }
  @Test
  public void testUpdateOnImplicitJoinFails() {
    Session s = openSession();
    Transaction t = s.beginTransaction();

    Human human = new Human();
    human.setName(new Name("Steve", 'E', null));

    Human mother = new Human();
    mother.setName(new Name("Jane", 'E', null));
    human.setMother(mother);

    s.save(human);
    s.save(mother);
    s.flush();

    t.commit();

    t = s.beginTransaction();
    try {
      s.createQuery("update Human set mother.name.initial = :initial")
          .setString("initial", "F")
          .executeUpdate();
      fail("update allowed across implicit join");
    } catch (QueryException e) {
    }

    s.createQuery("delete Human where mother is not null").executeUpdate();
    s.createQuery("delete Human").executeUpdate();
    t.commit();
    s.close();
  }
  @Test
  public void testUpdateSetNullUnionSubclass() {
    TestData data = new TestData();
    data.prepare();

    // These should reach out into *all* subclass tables...
    Session s = openSession();
    Transaction t = s.beginTransaction();

    int count = s.createQuery("update Vehicle set owner = 'Steve'").executeUpdate();
    assertEquals("incorrect restricted update count", 4, count);
    count = s.createQuery("update Vehicle set owner = null where owner = 'Steve'").executeUpdate();
    assertEquals("incorrect restricted update count", 4, count);

    try {
      count = s.createQuery("delete Vehicle where owner is null").executeUpdate();
      assertEquals("incorrect restricted delete count", 4, count);
    } catch (AssertionFailedError afe) {
      if (H2Dialect.class.isInstance(getDialect())) {
        // http://groups.google.com/group/h2-database/t/5548ff9fd3abdb7
        // this is fixed in H2 1.2.140
        count = s.createQuery("delete Vehicle").executeUpdate();
        assertEquals("incorrect count", 4, count);
      } else {
        throw afe;
      }
    }

    t.commit();
    s.close();

    data.cleanup();
  }
  @Test
  public void testTempTableGenerationIsolation() throws Throwable {
    Session s = openSession();
    s.beginTransaction();

    Truck truck = new Truck();
    truck.setVin("123t");
    truck.setOwner("Steve");
    s.save(truck);

    // manually flush the session to ensure the insert happens
    s.flush();

    // now issue a bulk delete against Car which should force the temp table to be
    // created.  we need to test to ensure that this does not cause the transaction
    // to be committed...
    s.createQuery("delete from Vehicle").executeUpdate();

    s.getTransaction().rollback();
    s.close();

    s = openSession();
    s.beginTransaction();
    List list = s.createQuery("from Car").list();
    assertEquals("temp table gen caused premature commit", 0, list.size());
    s.createQuery("delete from Car").executeUpdate();
    s.getTransaction().rollback();
    s.close();
  }
  @Test
  public void testInsertIntoSuperclassPropertiesFails() {
    TestData data = new TestData();
    data.prepare();

    Session s = openSession();
    Transaction t = s.beginTransaction();

    try {
      s.createQuery("insert into Human (id, bodyWeight) select id, bodyWeight from Lizard")
          .executeUpdate();
      fail("superclass prop insertion did not error");
    } catch (QueryException e) {
      // expected result
    }

    t.commit();
    t = s.beginTransaction();

    s.createQuery("delete Animal where mother is not null").executeUpdate();
    s.createQuery("delete Animal where father is not null").executeUpdate();
    s.createQuery("delete Animal").executeUpdate();

    t.commit();
    s.close();

    data.cleanup();
  }
  @Test
  public void testBasicOps() {
    Session session = openSession();
    session.beginTransaction();
    Country country = new Country("US", "United States of America");
    session.persist(country);
    Person person = new Person("Steve", new Address());
    person.getAddress().setLine1("123 Main");
    person.getAddress().setCity("Anywhere");
    person.getAddress().setCountry(country);
    person.getAddress().setPostalCode("123456789");
    session.persist(person);
    session.getTransaction().commit();
    session.close();

    session = openSession();
    session.beginTransaction();
    session.createQuery("from Person p where p.address.country.iso2 = 'US'").list();
    // same query!
    session.createQuery("from Person p where p.address.country.id = 'US'").list();
    person = (Person) session.load(Person.class, person.getId());
    session.delete(person);
    List countries = session.createQuery("from Country").list();
    assertEquals(1, countries.size());
    session.delete(countries.get(0));

    session.getTransaction().commit();
    session.close();
  }
Exemplo n.º 9
0
  @SuppressWarnings("unchecked")
  public Pagination<Product> getProductsAtPageIndex(int index) {
    Pagination<Product> pagination = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      session.beginTransaction();
      String hql = "select count(p) from Product p";
      Long count = (Long) session.createQuery(hql).uniqueResult();

      // 计算分页信息
      pagination = new Pagination<Product>(count.intValue(), index, 5);
      hql = "from Product";
      Query query = session.createQuery(hql);
      query.setFirstResult(pagination.getFirstResultOffset());
      log.info("offset: " + pagination.getFirstResultOffset());
      query.setMaxResults(5);
      // query.setResultTransformer(Transformers.aliasToBean(Product.class));

      pagination.setObjectList((List<Product>) query.list());
    } finally {
      session.getTransaction().commit();
    }

    return pagination;
  }
  @Test
  public void testSpecificQueryRegionEviction() {
    int entityCount = 10;
    insertDummyEntities(entityCount, 0);
    // miss 1 query list entities
    Session session = sf.openSession();
    Transaction txn = session.beginTransaction();
    Query query = session.createQuery("from " + DummyEntity.class.getName());
    query.setCacheable(true).setCacheRegion("newregionname");
    query.list();
    txn.commit();
    session.close();
    // query is cached

    // query is invalidated
    sf.getCache().evictQueryRegion("newregionname");

    // miss 1 query
    session = sf.openSession();
    txn = session.beginTransaction();
    query = session.createQuery("from " + DummyEntity.class.getName());
    query.setCacheable(true);
    query.list();
    txn.commit();
    session.close();

    assertEquals(0, sf.getStatistics().getQueryCacheHitCount());
    assertEquals(2, sf.getStatistics().getQueryCacheMissCount());
  }
  public void testCompositeUserType() {
    Session s = openSession();
    org.hibernate.Transaction t = s.beginTransaction();

    Transaction tran = new Transaction();
    tran.setDescription("a small transaction");
    tran.setValue(new MonetoryAmount(new BigDecimal(1.5), Currency.getInstance("USD")));
    s.persist(tran);

    List result =
        s.createQuery(
                "from Transaction tran where tran.value.amount > 1.0 and tran.value.currency = 'USD'")
            .list();
    assertEquals(result.size(), 1);
    tran.getValue().setCurrency(Currency.getInstance("AUD"));
    result =
        s.createQuery(
                "from Transaction tran where tran.value.amount > 1.0 and tran.value.currency = 'AUD'")
            .list();
    assertEquals(result.size(), 1);

    if (!(getDialect() instanceof HSQLDialect)) {

      result = s.createQuery("from Transaction txn where txn.value = (1.5, 'AUD')").list();
      assertEquals(result.size(), 1);
      result = s.createQuery("from Transaction where value = (1.5, 'AUD')").list();
      assertEquals(result.size(), 1);
    }

    s.delete(tran);
    t.commit();
    s.close();
  }
Exemplo n.º 12
0
 /**
  * 1. 可以看到select中可以直接使用一个对象表示当前所有的字段, 并且当查询出来之后直接赋值, 这样时非常强大的。 2.
  * 可以比较不同的select后面的值, 最终打包成的结果, 可以看到hibernate会为我们打包任何值对象, 并且这一切 都是自动的, 无须做任何操作
  */
 public void select() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     // 查询出那些存在邮箱的人
     List<Person> persons =
         session.createQuery("select p from Person as p inner join p.emails").list();
     for (Person person : persons) {
       System.out.println(person.getName());
     }
     // 查询出所有的人名, 可以看到这里distinct也可以使用
     List<String> names =
         session.createQuery("select distinct p.name from Person p inner join p.emails").list();
     for (String name : names) {
       System.out.println(name);
     }
     tx.rollback();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemplo n.º 13
0
  public List<Rating> getSchoolRating(Integer schoolId) {
    String HQL =
        "SELECT ratingCategoryType.id as catid, ratingCategoryType.categoryName as name, avg(rating) as rating, count(ratingCategoryType.id) as ratingCount, COALESCE(ratingCategoryType.image,'') as image from UserRating where school.id = :schoolId GROUP BY ratingCategoryType.id";
    HibernateUtil hibernateUtil = new HibernateUtil();
    Session session = hibernateUtil.openSession();

    Query query =
        session.createQuery(HQL).setResultTransformer(Transformers.aliasToBean(Rating.class));
    query.setParameter("schoolId", schoolId);
    session.flush();
    List<Rating> schoolRatings = query.list();
    if (schoolRatings.size() <= 0) {
      String newhql =
          "SELECT id as catid, categoryName as name, 0.0 as rating, 0L as ratingCount, COALESCE(image,'') as image from RatingCategoryType";
      Session newsession = hibernateUtil.openSession();
      Query newquery =
          newsession
              .createQuery(newhql)
              .setResultTransformer(Transformers.aliasToBean(Rating.class));
      newsession.flush();
      schoolRatings = newquery.list();
    }

    return schoolRatings;
  }
Exemplo n.º 14
0
  public void deleteById(Serializable id) {
    Session session = getSessionFactory().getCurrentSession();
    Transaction transaction = session.beginTransaction();

    // ɾ³ý²É¹ºÑ¯¼ÛÃ÷ϸ
    String hql = "delete from BuyOrderList where order.id=:orderId";
    Query query = session.createQuery(hql);
    query.setParameter("orderId", id);
    query.executeUpdate();

    // ɾ³ý¸½¼þ
    hql = "delete from Accessory where sort=:sort and dataId=:dataId";
    query = session.createQuery(hql);
    query.setParameter("sort", OrderState.CGGL_WLCG);
    query.setParameter("dataId", id);
    query.executeUpdate();

    // ÉóºË¼Ç¼
    hql = "delete from AuditMind where sort=:sort and dataId=:dataId";
    query = session.createQuery(hql);
    query.setParameter("sort", OrderState.CGGL_WLCG);
    query.setParameter("dataId", id);
    query.executeUpdate();

    // ɾ³ýÎïÁϲɹºµ¥
    hql = "delete from BuyOrder where id=:id";
    query = session.createQuery(hql);
    query.setParameter("id", id);
    query.executeUpdate();

    transaction.commit();
  }
  @Test
  public void testQueryIteration() throws Throwable {
    prepare();
    Session s = getSessionUnderTest();
    Silly silly = new Silly("silly");
    s.save(silly);
    s.flush();

    Iterator itr = s.createQuery("from Silly").iterate();
    assertTrue(itr.hasNext());
    Silly silly2 = (Silly) itr.next();
    assertEquals(silly, silly2);
    Hibernate.close(itr);

    itr = s.createQuery("from Silly").iterate();
    Iterator itr2 = s.createQuery("from Silly where name = 'silly'").iterate();

    assertTrue(itr.hasNext());
    assertEquals(silly, itr.next());
    assertTrue(itr2.hasNext());
    assertEquals(silly, itr2.next());

    Hibernate.close(itr);
    Hibernate.close(itr2);

    s.delete(silly);
    s.flush();

    release(s);
    done();
  }
Exemplo n.º 16
0
  public int findCountByParams(
      String sql, boolean isHql, int start, int limit, Map<String, Object> params) {
    log.info("finding count by sql : " + sql);
    Session session = getHibernateTemplate().getSessionFactory().openSession();

    Query query = null;
    if ("".equals(sql) || sql == null) {
      query = session.createQuery("from FamilyMember");
    } else {
      if (isHql) {
        query = session.createQuery(sql);
      } else {
        query = session.createSQLQuery(sql);
      }
    }
    if (start > -1) {
      query.setFirstResult(start);
    }
    if (limit > -1) {
      query.setMaxResults(limit);
    }
    if (params != null) {
      for (String key : params.keySet()) {
        query.setParameter(key, params.get(key));
      }
    }
    // return ((Integer) query.uniqueResult()).intValue();
    return query.list().size();
  }
  @Test
  public void testQueryScrolling() throws Throwable {
    prepare();
    Session s = getSessionUnderTest();
    Silly silly = new Silly("silly");
    s.save(silly);
    s.flush();

    ScrollableResults sr = s.createQuery("from Silly").scroll();
    assertTrue(sr.next());
    Silly silly2 = (Silly) sr.get(0);
    assertEquals(silly, silly2);
    sr.close();

    sr = s.createQuery("from Silly").scroll();
    ScrollableResults sr2 = s.createQuery("from Silly where name = 'silly'").scroll();

    assertTrue(sr.next());
    assertEquals(silly, sr.get(0));
    assertTrue(sr2.next());
    assertEquals(silly, sr2.get(0));

    sr.close();
    sr2.close();

    s.delete(silly);
    s.flush();

    release(s);
    done();
  }
Exemplo n.º 18
0
 protected RoomFeature lookupFeature(
     org.hibernate.Session hibSession, Long featureId, boolean future, Long sessionId) {
   if (featureId == null) return null;
   if (future) {
     RoomFeature feature =
         (DepartmentRoomFeature)
             hibSession
                 .createQuery(
                     "select f from DepartmentRoomFeature f, DepartmentRoomFeature o where o.uniqueId = :originalId and f.department.session.uniqueId = :sessionId "
                         + "and f.abbv = o.abbv and f.department.deptCode = o.department.deptCode")
                 .setLong("sessionId", sessionId)
                 .setLong("originalId", featureId)
                 .setCacheable(true)
                 .setMaxResults(1)
                 .uniqueResult();
     if (feature == null)
       feature =
           (GlobalRoomFeature)
               hibSession
                   .createQuery(
                       "select f from GlobalRoomFeature f, GlobalRoomFeature o where o.uniqueId = :originalId and f.session.uniqueId = :sessionId "
                           + "and f.abbv = o.abbv")
                   .setLong("sessionId", sessionId)
                   .setLong("originalId", featureId)
                   .setCacheable(true)
                   .setMaxResults(1)
                   .uniqueResult();
     return feature;
   } else {
     return RoomFeatureDAO.getInstance().get(featureId, hibSession);
   }
 }
  @Test
  public void testInsertWithMismatchedTypes() {
    TestData data = new TestData();
    data.prepare();

    Session s = openSession();
    Transaction t = s.beginTransaction();
    try {
      s.createQuery("insert into Pickup (owner, vin, id) select id, vin, owner from Car")
          .executeUpdate();
      fail("mismatched types did not error");
    } catch (QueryException e) {
      // expected result
    }

    t.commit();
    t = s.beginTransaction();

    s.createQuery("delete Vehicle").executeUpdate();

    t.commit();
    s.close();

    data.cleanup();
  }
Exemplo n.º 20
0
  public void testLoadingStrategies() {
    Session s = openSession();
    s.beginTransaction();
    Customer cust = new Customer("Acme, Inc.");
    Order order = new Order(new Order.Id(cust, 1));
    cust.getOrders().add(order);
    s.save(cust);
    s.getTransaction().commit();
    s.close();

    s = openSession();
    s.beginTransaction();

    cust = (Customer) s.get(Customer.class, cust.getId());
    assertEquals(1, cust.getOrders().size());
    s.clear();

    cust = (Customer) s.createQuery("from Customer").uniqueResult();
    assertEquals(1, cust.getOrders().size());
    s.clear();

    cust = (Customer) s.createQuery("from Customer c join fetch c.orders").uniqueResult();
    assertEquals(1, cust.getOrders().size());
    s.clear();

    s.delete(cust);
    s.getTransaction().commit();
    s.close();
  }
  @Test
  public void testInsertAcrossMappedJoinFails() {
    TestData data = new TestData();
    data.prepare();

    Session s = openSession();
    Transaction t = s.beginTransaction();

    try {
      s.createQuery("insert into Joiner (name, joinedName) select vin, owner from Car")
          .executeUpdate();
      fail("mapped-join insertion did not error");
    } catch (QueryException e) {
      // expected result
    }

    t.commit();
    t = s.beginTransaction();

    s.createQuery("delete Joiner").executeUpdate();
    s.createQuery("delete Vehicle").executeUpdate();

    t.commit();
    s.close();

    data.cleanup();
  }
  /**
   * Test that the legacy manual disconnect()/reconnect() chain works as expected in the given
   * environment. Similar to {@link #testManualDisconnectChain} expect that here we force the
   * session to acquire and hold JDBC resources prior to disconnecting.
   */
  @Test
  public final void testManualDisconnectWithOpenResources() throws Throwable {
    prepare();
    Session sessionUnderTest = getSessionUnderTest();

    Silly silly = new Silly("tester");
    sessionUnderTest.save(silly);
    sessionUnderTest.flush();

    sessionUnderTest.createQuery("from Silly").iterate();

    disconnect(sessionUnderTest);
    SerializationHelper.serialize(sessionUnderTest);
    checkSerializedState(sessionUnderTest);

    reconnect(sessionUnderTest);
    sessionUnderTest.createQuery("from Silly").scroll();

    disconnect(sessionUnderTest);
    SerializationHelper.serialize(sessionUnderTest);
    checkSerializedState(sessionUnderTest);

    reconnect(sessionUnderTest);
    sessionUnderTest.delete(silly);
    sessionUnderTest.flush();

    release(sessionUnderTest);
    done();
  }
  @Test
  public void testUpdateOnMammal() {
    TestData data = new TestData();
    data.prepare();

    Session s = openSession();
    Transaction t = s.beginTransaction();

    int count = s.createQuery("update Mammal set description = description").executeUpdate();
    assertEquals("incorrect update count against 'middle' of joined-subclass hierarchy", 2, count);

    count = s.createQuery("update Mammal set bodyWeight = 25").executeUpdate();
    assertEquals("incorrect update count against 'middle' of joined-subclass hierarchy", 2, count);

    if (!(getDialect() instanceof MySQLDialect)) {
      // MySQL does not support (even un-correlated) subqueries against the update-mutating table
      count =
          s.createQuery("update Mammal set bodyWeight = ( select max(bodyWeight) from Animal )")
              .executeUpdate();
      assertEquals(
          "incorrect update count against 'middle' of joined-subclass hierarchy", 2, count);
    }

    t.commit();
    s.close();

    data.cleanup();
  }
Exemplo n.º 24
0
  private static void pecas() {
    Session session = HibernateUtil.getSession();
    session.beginTransaction();

    for (String linha : getPecasFromCSV()) {
      String[] item = linha.split(";");

      String hqlMarca = "from Marca m where m.nome = :nome ";
      Query queryMarca = session.createQuery(hqlMarca).setString("nome", item[2]);
      Marca marca = (Marca) queryMarca.uniqueResult();

      if (marca == null || marca.getId() == 0) {
        marca = new Marca();
        marca.setNome(item[2]);
        session.saveOrUpdate(marca);
      }

      Peca peca = new Peca();
      peca.setNome(item[0]);
      peca.setDescricao(item[1] + " - " + item[3]);
      peca.setQuantidade(50);
      peca.setMarca(marca);
      session.saveOrUpdate(peca);

      TarifarioPeca tarifarioPeca = new TarifarioPeca();
      tarifarioPeca.setData(new Date());
      tarifarioPeca.setValor(Double.parseDouble(item[4]));
      tarifarioPeca.setMarkup(25);
      tarifarioPeca.setValorVenda(
          (tarifarioPeca.getValor() * (25 / 100)) + tarifarioPeca.getValor());
      tarifarioPeca.setPeca(peca);
      session.saveOrUpdate(tarifarioPeca);

      String hqlTipoServico = "from TipoServico m where m.nome = :nome ";
      Query queryTipoServico =
          session.createQuery(hqlTipoServico).setString("nome", "Troca de peça");
      TipoServico tipoServico = (TipoServico) queryTipoServico.uniqueResult();

      if (tipoServico == null || tipoServico.getId() == 0) {
        tipoServico = new TipoServico();
        tipoServico.setNome("Troca de peça");
        session.saveOrUpdate(tipoServico);
      }

      Servico servico = new Servico();
      servico.setNome(item[5]);
      servico.setDescricao(item[5]);
      servico.setTipoServico(tipoServico);
      session.saveOrUpdate(servico);

      TarifarioServico tarifarioServico = new TarifarioServico();
      tarifarioServico.setData(new Date());
      tarifarioServico.setServico(servico);
      tarifarioServico.setValor(Double.parseDouble(item[6]));
      session.saveOrUpdate(tarifarioServico);
    }

    session.getTransaction().commit();
    System.out.println("Peças importadas!");
  }
Exemplo n.º 25
0
  @RequestMapping(value = "convert")
  @Transactional(propagation = Propagation.REQUIRES_NEW)
  public String validateImages() throws Exception {
    final Session session = sessionFactory.getCurrentSession();
    final Query query =
        session.createQuery(
            "select id, name from billiongoods.server.warehouse.impl.HibernateCategory");
    final List list = query.list();
    for (Object o : list) {
      final Object[] v = (Object[]) o;

      final Integer id = (Integer) v[0];
      final String name = (String) v[1];

      final String s = symbolicConverter.generateSymbolic(name);

      final Query query1 =
          session.createQuery(
              "update billiongoods.server.warehouse.impl.HibernateCategory set symbolic=:n where id=:id");
      query1.setParameter("id", id);
      query1.setParameter("n", s);
      query1.executeUpdate();
    }
    return "/content/maintain/main";
  }
Exemplo n.º 26
0
 public void deleteUser(WkTUser user) {
   // 首先删除用户角色关系
   Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
   session.beginTransaction();
   String deleteUserRole = "delete WkTUserole as u_r where u_r.id.kuId=?";
   Query dUserRole = session.createQuery(deleteUserRole);
   dUserRole.setLong(0, user.getKuId());
   dUserRole.executeUpdate();
   // 还需要删除用户发布信息、消息等
   String deleteNR = "delete XyNUrd as xnurd where xnurd.id.kuId=?";
   Query updateNRQ = session.createQuery(deleteNR);
   updateNRQ.setLong(0, user.getKuId());
   updateNRQ.executeUpdate();
   String deleteM = "delete XyMReceiver as xmr where xmr.id.kuId=?";
   Query updateM = session.createQuery(deleteM);
   updateM.setLong(0, user.getKuId());
   updateM.executeUpdate();
   String deleteN = "delete XyMessage as xm where xm.kuId=?";
   Query updateN = session.createQuery(deleteN);
   updateN.setLong(0, user.getKuId());
   updateN.executeUpdate();
   session.getTransaction().commit();
   // 删除用户
   getHibernateTemplate().delete(user);
 }
Exemplo n.º 27
0
  @Override
  public List<Forum> getForumsOfaUser(int userId) {
    // TODO Auto-generated method stub
    List<Forum> forums = new ArrayList<Forum>();
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      Query query = session.createQuery("from Subscription where userId = :userId");
      query.setString("userId", String.valueOf(userId));
      List<Subscription> userSubscribedGroups = query.list();
      for (Subscription subsc : userSubscribedGroups) {
        query = session.createQuery("from Forum where forumId = :forumId");
        query.setParameter("forumId", subsc.getForumId());
        // add this to a list variable query.uniqueResult();
        forums.add((Forum) query.uniqueResult());
      }

    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return forums;
  }
  public void addMansion(Mansion m) {

    Session session = sf.getCurrentSession();

    session.beginTransaction();

    session.save(m);

    session.getTransaction().commit();

    Session session2 = sf.getCurrentSession();

    session2.beginTransaction();

    Query query = session2.createQuery("from Mansion");
    List<Mansion> mlist = query.list();
    for (Mansion onem : mlist) {
      System.out.println(onem.getA().size());
    }

    Query query2 = session2.createQuery("from Aristocrat");
    List<Aristocrat> alist = query2.list();
    for (Aristocrat onea : alist) {
      System.out.println("An aristocrat...");
    }

    session2.close();
  }
Exemplo n.º 29
0
 @Override
 public User getLikesCommentsAndBlogs(User user) {
   Session session = factory.openSession();
   @SuppressWarnings("unchecked")
   List<Long> like =
       session
           .createQuery("Select l.blogId from Likes as l where l.userId = :userId")
           .setParameter("userId", user.getUserId())
           .list();
   @SuppressWarnings("unchecked")
   List<Long> blog =
       session
           .createQuery("Select b.blogId from Blog as b where b.userId = :userId")
           .setParameter(":userId", user.getUserId())
           .list();
   @SuppressWarnings("unchecked")
   List<Long> comment =
       session
           .createQuery("Seelct c.commentId from Comment as c where c.userId = :userId")
           .setParameter(":userId", user.getUserId())
           .list();
   Set<Long> likeList = new HashSet<Long>(like);
   Set<Long> blogList = new HashSet<Long>(blog);
   Set<Long> commentList = new HashSet<Long>(comment);
   user.setLikes(likeList);
   user.setBlogs(blogList);
   user.setComments(commentList);
   return user;
 }
  @Test(description = "same queries with where clause in different order must nor hit cache")
  public void same_queries_with_where_clause_in_different_order_must_nor_hit_cache() {
    long initialHits = sessionFactory.getStatistics().getQueryCacheHitCount();
    Session session = getSession();
    List<Item> items1 =
        session
            .createQuery("from Item i where i.name=:name and i.status=:status")
            .setParameter("name", "test")
            .setParameter("status", true)
            .setCacheable(true)
            .list();

    Session newSession = sessionFactory.openSession(); // No session hit
    List<Item> items2 =
        newSession
            .createQuery("from Item i where i.status=:status and i.name=:name")
            .setParameter("name", "test")
            .setParameter("status", true)
            .setCacheable(true)
            .list();

    assertThat(items1).isEqualTo(items2); // Same content

    assertThat(sessionFactory.getStatistics().getQueryCacheHitCount()).isEqualTo(initialHits);
  }