@Test
  public void testWrappedFromEntityManagerAPI() throws Exception {
    buildArchive();

    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpajtastandalone");
    assertThat(HibernateEntityManagerFactory.class.isAssignableFrom(emf.getClass())).isTrue();
    SessionFactory factory = ((HibernateEntityManagerFactory) emf).getSessionFactory();
    assertThat(factory.getClass()).isEqualTo(OgmSessionFactory.class);

    Session s = factory.openSession();
    assertThat(s.getClass()).isEqualTo(OgmSession.class);
    assertThat(s.getSessionFactory().getClass()).isEqualTo(OgmSessionFactory.class);

    Cavalier cavalier = new Cavalier();
    cavalier.setName("Caroline");

    EntityManager em = emf.createEntityManager();
    assertThat(em.unwrap(Session.class).getClass()).isEqualTo(OgmSession.class);
    assertThat(em.getDelegate().getClass()).isEqualTo(OgmSession.class);

    s.save(cavalier);

    Cavalier c = (Cavalier) s.get(Cavalier.class, cavalier.getId());
    assertTrue(c.getId().equals(cavalier.getId()));
    assertTrue(c.getName().equals(cavalier.getName()));

    em.close();

    emf.close();
  }
  @AggrEventsTransactional
  @Override
  public void evictAggregates(Map<Class<?>, Collection<Serializable>> entitiesToEvict) {
    int evictedEntities = 0;
    int evictedCollections = 0;

    final Session session = getEntityManager().unwrap(Session.class);
    final SessionFactory sessionFactory = session.getSessionFactory();
    final Cache cache = sessionFactory.getCache();

    for (final Entry<Class<?>, Collection<Serializable>> evictedEntityEntry :
        entitiesToEvict.entrySet()) {
      final Class<?> entityClass = evictedEntityEntry.getKey();
      final List<String> collectionRoles = getCollectionRoles(sessionFactory, entityClass);

      for (final Serializable id : evictedEntityEntry.getValue()) {
        cache.evictEntity(entityClass, id);
        evictedEntities++;

        for (final String collectionRole : collectionRoles) {
          cache.evictCollection(collectionRole, id);
          evictedCollections++;
        }
      }
    }

    logger.debug(
        "Evicted {} entities and {} collections from hibernate caches",
        evictedEntities,
        evictedCollections);
  }
  private static void createTable(String xml, CgFormHeadEntity table, Session session)
      throws HibernateException, SQLException, DBException {

    // FIXME 考虑JNDI的情况
    // 重新构建一个Configuration
    org.hibernate.cfg.Configuration newconf = new org.hibernate.cfg.Configuration();
    newconf
        .addXML(xml)
        .setProperty(
            "hibernate.dialect",
            ((SessionImpl) session).getFactory().getDialect().getClass().getName());
    //
    // .setProperty("hibernate.connection.username",propertiesUtil.readProperty("jdbc.username.jeecg"))
    //
    // .setProperty("hibernate.connection.password",propertiesUtil.readProperty("jdbc.password.jeecg"))
    //       .setProperty("hibernate.dialect",propertiesUtil.readProperty("hibernate.dialect"))
    //       .setProperty("hibernate.connection.url",propertiesUtil.readProperty("jdbc.url.jeecg"))
    //
    // .setProperty("hibernate.connection.driver_class",propertiesUtil.readProperty("jdbc.driver.class"));
    //
    SchemaExport dbExport;
    dbExport =
        new SchemaExport(
            newconf,
            SessionFactoryUtils.getDataSource(session.getSessionFactory()).getConnection());
    dbExport.execute(true, true, false, true);
    // 抛出执行异常,抛出第一个即可
    @SuppressWarnings("unchecked")
    List<Exception> exceptionList = dbExport.getExceptions();
    for (Exception exception : exceptionList) {
      throw new DBException(exception.getMessage());
    }
  }
  /**
   * Create an audit reader associated with an open session.
   *
   * @param session An open session.
   * @return An audit reader associated with the given sesison. It shouldn't be used after the
   *     session is closed.
   * @throws AuditException When the given required listeners aren't installed.
   */
  public static AuditReader get(Session session) throws AuditException {
    SessionImplementor sessionImpl;
    if (!(session instanceof SessionImplementor)) {
      sessionImpl = (SessionImplementor) session.getSessionFactory().getCurrentSession();
    } else {
      sessionImpl = (SessionImplementor) session;
    }

    // todo : I wonder if there is a better means to do this via "named lookup" based on the session
    // factory name/uuid
    final EventListenerRegistry listenerRegistry =
        sessionImpl.getFactory().getServiceRegistry().getService(EventListenerRegistry.class);

    for (PostInsertEventListener listener :
        listenerRegistry.getEventListenerGroup(EventType.POST_INSERT).listeners()) {
      if (listener instanceof EnversListener) {
        // todo : slightly different from original code in that I am not checking the other listener
        // groups...
        return new AuditReaderImpl(
            ((EnversListener) listener).getAuditConfiguration(), session, sessionImpl);
      }
    }

    throw new AuditException("Envers listeners were not properly registered");
  }
Ejemplo n.º 5
0
  public static JasperPrint generateRecapAdressesClients(Date dateDebut, Date dateFin) {

    JasperPrint printImprCheques = new JasperPrint();

    Connection conn = null;
    long start = System.currentTimeMillis();
    try {

      Map<String, Object> paramFacture = new HashMap<String, Object>();
      paramFacture.put("debut", dateDebut);
      paramFacture.put("fin", dateFin);

      org.hibernate.Session session = CEFXUtil.getSessionFactory().getCurrentSession();

      SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
      ConnectionProvider cp = sfi.getConnectionProvider();
      conn = cp.getConnection();

      printImprCheques =
          JasperFillManager.fillReport("src/cefx/report/AdresseAnnee.jasper", paramFacture, conn);

    } catch (Exception e) {
      throw new RuntimeException("Impossible de générer le recap", e);
    } finally {
      //                     it's your responsibility to close the connection, don't forget it!
      if (conn != null) {
        try {
          conn.close();
        } catch (Exception e) {
        }
      }
    }

    return printImprCheques;
  }
  /**
   * Binds a parameter value to a query parameter.
   *
   * @param parameter the report parameter
   */
  protected void setParameter(JRValueParameter parameter) {
    String hqlParamName = getHqlParameterName(parameter.getName());
    Class<?> clazz = parameter.getValueClass();
    Object parameterValue = parameter.getValue();

    if (log.isDebugEnabled()) {
      log.debug(
          "Parameter " + hqlParamName + " of type " + clazz.getName() + ": " + parameterValue);
    }

    Type type = hibernateTypeMap.get(clazz);

    if (type != null) {
      query.setParameter(hqlParamName, parameterValue, type);
    } else if (Collection.class.isAssignableFrom(clazz)) {
      query.setParameterList(hqlParamName, (Collection<?>) parameterValue);
    } else {
      if (session.getSessionFactory().getClassMetadata(clazz)
          != null) // param type is a hibernate mapped entity
      {
        query.setEntity(hqlParamName, parameterValue);
      } else // let hibernate try to guess the type
      {
        query.setParameter(hqlParamName, parameterValue);
      }
    }
  }
  /**
   * @param writer
   * @param includeHistory
   * @param session
   * @throws DataAccessException
   * @throws HibernateException
   */
  private void writeObjects(
      final Writer writer,
      final boolean includeHistory,
      final Session session,
      final boolean preserveIds)
      throws DataAccessException, HibernateException {
    // Container für die Objekte
    final List<Object> all = new ArrayList<Object>();
    final XStream stream = initXStream(session, true);
    final XStream defaultXStream = initXStream(session, false);

    session.flush();
    // Alles laden
    List<?> list = session.createQuery("select o from java.lang.Object o").setReadOnly(true).list();
    list = (List<?>) CollectionUtils.select(list, PredicateUtils.uniquePredicate());
    final int size = list.size();
    log.info("Writing " + size + " objects");
    for (final Iterator<?> it = list.iterator(); it.hasNext(); ) {
      final Object obj = it.next();
      if (log.isDebugEnabled()) {
        log.debug("loaded object " + obj);
      }
      if ((obj instanceof HistoryEntry || obj instanceof PropertyDelta)
          && includeHistory == false) {
        continue;
      }
      Hibernate.initialize(obj);
      final Class<?> targetClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
      final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(targetClass);
      if (classMetadata == null) {
        log.fatal("Can't init " + obj + " of type " + targetClass);
        continue;
      }
      // initalisierung des Objekts...
      defaultXStream.marshal(obj, new CompactWriter(new NullWriter()));

      if (preserveIds == false) {
        // Nun kann die ID gelöscht werden
        classMetadata.setIdentifier(obj, null, EntityMode.POJO);
      }
      if (log.isDebugEnabled()) {
        log.debug("loading evicted object " + obj);
      }
      if (this.ignoreFromTopLevelListing.contains(targetClass) == false) {
        all.add(obj);
      }
    }
    // und schreiben
    try {
      writer.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
    } catch (final IOException ex) {
      // ignore, will fail on stream.marshal()
    }
    log.info("Wrote " + all.size() + " objects");
    final MarshallingStrategy marshallingStrategy = new ProxyIdRefMarshallingStrategy();
    stream.setMarshallingStrategy(marshallingStrategy);
    stream.marshal(all, new PrettyPrintWriter(writer));
  }
Ejemplo n.º 8
0
 @Override
 @SuppressWarnings("unchecked")
 public Map<String, Object> extractEntityTuple(Session session, EntityKey key) {
   MongoDBDatastoreProvider provider = MongoDBTestHelper.getProvider(session.getSessionFactory());
   DBObject finder = new BasicDBObject(MongoDBDialect.ID_FIELDNAME, key.getColumnValues()[0]);
   DBObject result = provider.getDatabase().getCollection(key.getTable()).findOne(finder);
   replaceIdentifierColumnName(result, key);
   return result.toMap();
 }
Ejemplo n.º 9
0
  private void addChildExampleCriteria(Object exampleInstance, Criteria criteria, Session sesion) {
    ClassMetadata metadata =
        sesion.getSessionFactory().getClassMetadata(exampleInstance.getClass());

    String[] propertyNames = metadata.getPropertyNames();
    Type[] propertyTypes = metadata.getPropertyTypes();

    // see if this example instance has any properties that are entities
    for (int i = 0; i < propertyNames.length; i++) {

      String propertyName = propertyNames[i];
      Type propertyType = propertyTypes[i];

      if (propertyType instanceof EntityType) {
        // this property is an association - Hibernate's Example ignores
        // these
        Object value = metadata.getPropertyValue(exampleInstance, propertyName, EntityMode.POJO);

        if (value != null) {

          ClassMetadata childMetadata =
              sesion.getSessionFactory().getClassMetadata(value.getClass());
          Criteria childCriteria = criteria.createCriteria(propertyName);

          if (childMetadata.hasIdentifierProperty()) {

            Object id = childMetadata.getIdentifier(value, EntityMode.POJO);
            if (id != null) {
              // add the identifier to the child criteria
              childCriteria.add(Restrictions.eq(childMetadata.getIdentifierPropertyName(), id));
            }
          }

          // add the entity's fields as Example fields
          childCriteria.add(Example.create(value));

          // add this entity's associations
          addChildExampleCriteria(value, childCriteria, sesion);
        }
      }
    } // ~for
  }
Ejemplo n.º 10
0
 public void clear2ndLevelHibernateCache() {
   Session s = (Session) em.getDelegate();
   SessionFactory sf = s.getSessionFactory();
   //        sf.evict(User.class);
   //        sf.getCache().evictEntity(User.class, BaseEntity.START_SEQ);
   //        sf.getCache().evictEntityRegion(User.class);
   sf.getCache().evictQueryRegions();
   sf.getCache().evictDefaultQueryRegion();
   sf.getCache().evictCollectionRegions();
   sf.getCache().evictEntityRegions();
 }
Ejemplo n.º 11
0
 public static void main(final String[] args) throws Exception {
   final Session session = getSession();
   try {
     System.out.println("querying all the managed entities...");
     final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
     for (Object key : metadataMap.keySet()) {
       final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
       final String entityName = classMetadata.getEntityName();
       final Query query = session.createQuery("from " + entityName);
       System.out.println("executing: " + query.getQueryString());
       for (Object o : query.list()) {
         System.out.println("  " + o);
       }
     }
   } finally {
     session.close();
   }
 }
  @Test
  public void testWrappedFromEntityManagerAPI() throws Exception {
    final EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("ogm", TestHelper.getEnvironmentProperties());
    assertThat(HibernateEntityManagerFactory.class.isAssignableFrom(emf.getClass())).isTrue();
    SessionFactory factory = ((HibernateEntityManagerFactory) emf).getSessionFactory();
    assertThat(factory.getClass()).isEqualTo(OgmSessionFactoryImpl.class);

    Session s = factory.openSession();
    assertThat(s.getClass()).isEqualTo(OgmSessionImpl.class);
    assertThat(s.getSessionFactory().getClass()).isEqualTo(OgmSessionFactoryImpl.class);
    s.close();

    EntityManager em = emf.createEntityManager();
    assertThat(em.unwrap(Session.class) instanceof OgmSession);
    assertThat(em.getDelegate().getClass()).isEqualTo(OgmSessionImpl.class);

    em.close();

    emf.close();
  }
Ejemplo n.º 13
0
  public static JasperPrint generateFacture(Integer numFacture) {

    Connection conn = null;
    JasperPrint printFacture = new JasperPrint();

    long start = System.currentTimeMillis();

    try {

      Map<String, Object> paramFacture = new HashMap<String, Object>();
      paramFacture.put("num_commande", numFacture);

      org.hibernate.Session session = CEFXUtil.getSessionFactory().getCurrentSession();

      SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
      ConnectionProvider cp = sfi.getConnectionProvider();
      conn = cp.getConnection();

      printFacture =
          JasperFillManager.fillReport("src/cefx/report/FactureCE.jasper", paramFacture, conn);
      //    JasperPrint printBDC =
      // JasperFillManager.fillReport("src/cefx/report/BonDeCommande.jasper", paramFacture, conn);

    } catch (Exception e) {
      throw new RuntimeException("Impossible de générer la Facture", e);
      //  COMMANDE ENREGISTREE MAIS NON IMPRIMEE
    } finally {
      //                     it's your responsibility to close the connection, don't forget it!
      if (conn != null) {
        try {
          conn.close();
        } catch (Exception e) {
        }
      }
    }

    return printFacture;
  }
Ejemplo n.º 14
0
  /**
   * 获取数据库中列的描述
   *
   * @param tableName
   * @param session
   * @return
   * @throws SQLException
   */
  public static Map<String, ColumnMeta> getColumnMetadataFormDataBase(
      String schemaName, String tableName, Session session) throws SQLException {
    Connection conn =
        SessionFactoryUtils.getDataSource(session.getSessionFactory()).getConnection();
    DatabaseMetaData dbMetaData = conn.getMetaData();
    ResultSet rs = dbMetaData.getColumns(null, schemaName, tableName, "%");
    ColumnMeta columnMeta;
    Map<String, ColumnMeta> columnMap = new HashMap<String, ColumnMeta>();
    while (rs.next()) {
      columnMeta = new ColumnMeta();
      columnMeta.setTableName(rs.getString("COLUMN_NAME").toLowerCase());
      columnMeta.setColumnName(rs.getString("COLUMN_NAME").toLowerCase());
      columnMeta.setColunmType(
          dbTableHandle.getMatchClassTypeByDataType(
              rs.getString("TYPE_NAME"), rs.getInt("DECIMAL_DIGITS")));
      columnMeta.setColumnSize(rs.getInt("COLUMN_SIZE"));
      columnMeta.setDecimalDigits(rs.getInt("DECIMAL_DIGITS"));
      columnMeta.setIsNullable(rs.getInt("NULLABLE") == 1 ? "Y" : "N");
      columnMeta.setComment(rs.getString("REMARKS"));
      columnMeta.setFieldDefault(
          judgeIsNumber(rs.getString("COLUMN_DEF")) == null
              ? ""
              : judgeIsNumber(rs.getString("COLUMN_DEF")));
      logger.info(
          "getColumnMetadataFormDataBase --->COLUMN_NAME:"
              + rs.getString("COLUMN_NAME")
              + " TYPE_NAME :"
              + rs.getString("TYPE_NAME")
              + " DECIMAL_DIGITS:"
              + rs.getInt("DECIMAL_DIGITS")
              + " COLUMN_SIZE:"
              + rs.getInt("COLUMN_SIZE"));
      columnMap.put(rs.getString("COLUMN_NAME").toLowerCase(), columnMeta);
    }

    return columnMap;
  }
Ejemplo n.º 15
0
  @Test
  public void entityMappingTest() {
    try {
      log.info("querying all the managed entities...");
      final Map<String, ClassMetadata> metadataMap =
          session.getSessionFactory().getAllClassMetadata();

      for (Object key : metadataMap.keySet()) {
        final ClassMetadata classMetadata = metadataMap.get(key);
        final String entityName = classMetadata.getEntityName();
        final Query query = session.createQuery("from " + entityName);
        query.setCacheable(true);

        log.info("executing hql= " + query.getQueryString());

        for (Object o : query.list()) {
          log.info("IEntity=  " + o);
        }
      }
    } finally {
      session.flush();
    }
    log.info("성공했습니다.");
  }
Ejemplo n.º 16
0
 public static void dropSchemaAndDatabase(Session session) {
   if (session != null) {
     dropSchemaAndDatabase(session.getSessionFactory());
   }
 }
  @Test
  public void testCache() {
    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          entityManager.persist(new Person());
          entityManager.persist(new Person());
          Person aPerson = new Person();
          aPerson.setName("John Doe");
          aPerson.setCode("unique-code");
          entityManager.persist(aPerson);
          return aPerson;
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("Jpa load by id");
          // tag::caching-entity-jpa-example[]
          Person person = entityManager.find(Person.class, 1L);
          // end::caching-entity-jpa-example[]
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("Native load by id");
          Session session = entityManager.unwrap(Session.class);
          // tag::caching-entity-native-example[]
          Person person = session.get(Person.class, 1L);
          // end::caching-entity-native-example[]
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("Native load by natural-id");
          Session session = entityManager.unwrap(Session.class);
          // tag::caching-entity-natural-id-example[]
          Person person = session.byNaturalId(Person.class).using("code", "unique-code").load();
          // end::caching-entity-natural-id-example[]
          assertNotNull(person);
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("Jpa query cache");
          // tag::caching-query-jpa-example[]
          List<Person> persons =
              entityManager
                  .createQuery(
                      "select p " + "from Person p " + "where p.name = :name", Person.class)
                  .setParameter("name", "John Doe")
                  .setHint("org.hibernate.cacheable", "true")
                  .getResultList();
          // end::caching-query-jpa-example[]
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("Native query cache");
          Session session = entityManager.unwrap(Session.class);
          // tag::caching-query-native-example[]
          List<Person> persons =
              session
                  .createQuery("select p " + "from Person p " + "where p.name = :name")
                  .setParameter("name", "John Doe")
                  .setCacheable(true)
                  .list();
          // end::caching-query-native-example[]
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("Jpa query cache region");
          // tag::caching-query-region-jpa-example[]
          List<Person> persons =
              entityManager
                  .createQuery("select p " + "from Person p " + "where p.id > :id", Person.class)
                  .setParameter("id", 0L)
                  .setHint(QueryHints.HINT_CACHEABLE, "true")
                  .setHint(QueryHints.HINT_CACHE_REGION, "query.cache.person")
                  .getResultList();
          // end::caching-query-region-jpa-example[]
        });
    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("Native query cache");
          Session session = entityManager.unwrap(Session.class);
          // tag::caching-query-region-native-example[]
          List<Person> persons =
              session
                  .createQuery("select p " + "from Person p " + "where p.id > :id")
                  .setParameter("id", 0L)
                  .setCacheable(true)
                  .setCacheRegion("query.cache.person")
                  .list();
          // end::caching-query-region-native-example[]
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("Jpa query cache store mode ");
          // tag::caching-query-region-store-mode-jpa-example[]
          List<Person> persons =
              entityManager
                  .createQuery("select p " + "from Person p " + "where p.id > :id", Person.class)
                  .setParameter("id", 0L)
                  .setHint(QueryHints.HINT_CACHEABLE, "true")
                  .setHint(QueryHints.HINT_CACHE_REGION, "query.cache.person")
                  .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
                  .getResultList();
          // end::caching-query-region-store-mode-jpa-example[]
        });
    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("Native query cache store mode");
          Session session = entityManager.unwrap(Session.class);
          // tag::caching-query-region-store-mode-native-example[]
          List<Person> persons =
              session
                  .createQuery("select p " + "from Person p " + "where p.id > :id")
                  .setParameter("id", 0L)
                  .setCacheable(true)
                  .setCacheRegion("query.cache.person")
                  .setCacheMode(CacheMode.REFRESH)
                  .list();
          // end::caching-query-region-store-mode-native-example[]
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          Session session = entityManager.unwrap(Session.class);
          // tag::caching-statistics-example[]
          Statistics statistics = session.getSessionFactory().getStatistics();
          SecondLevelCacheStatistics secondLevelCacheStatistics =
              statistics.getSecondLevelCacheStatistics("query.cache.person");
          long hitCount = secondLevelCacheStatistics.getHitCount();
          long missCount = secondLevelCacheStatistics.getMissCount();
          double hitRatio = (double) hitCount / (hitCount + missCount);
          // end::caching-statistics-example[]
          return hitRatio;
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("Native query cache store mode");
          Session session = entityManager.unwrap(Session.class);
          // tag::caching-query-region-native-evict-example[]
          session.getSessionFactory().getCache().evictQueryRegion("query.cache.person");
          // end::caching-query-region-native-evict-example[]
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          // tag::caching-management-cache-mode-entity-jpa-example[]
          Map<String, Object> hints = new HashMap<>();
          hints.put("javax.persistence.cache.retrieveMode ", CacheRetrieveMode.USE);
          hints.put("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH);
          Person person = entityManager.find(Person.class, 1L, hints);
          // end::caching-management-cache-mode-entity-jpa-example[]
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          Session session = entityManager.unwrap(Session.class);
          // tag::caching-management-cache-mode-entity-native-example[]
          session.setCacheMode(CacheMode.REFRESH);
          Person person = session.get(Person.class, 1L);
          // end::caching-management-cache-mode-entity-native-example[]
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          // tag::caching-management-cache-mode-query-jpa-example[]
          List<Person> persons =
              entityManager
                  .createQuery("select p from Person p", Person.class)
                  .setHint(QueryHints.HINT_CACHEABLE, "true")
                  .setHint("javax.persistence.cache.retrieveMode ", CacheRetrieveMode.USE)
                  .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
                  .getResultList();
          // end::caching-management-cache-mode-query-jpa-example[]

          // tag::caching-management-evict-jpa-example[]
          entityManager.getEntityManagerFactory().getCache().evict(Person.class);
          // end::caching-management-evict-jpa-example[]
        });

    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          Session session = entityManager.unwrap(Session.class);
          // tag::caching-management-cache-mode-query-native-example[]
          List<Person> persons =
              session
                  .createQuery("select p from Person p")
                  .setCacheable(true)
                  .setCacheMode(CacheMode.REFRESH)
                  .list();
          // end::caching-management-cache-mode-query-native-example[]

          // tag::caching-management-evict-native-example[]
          session.getSessionFactory().getCache().evictQueryRegion("query.cache.person");
          // end::caching-management-evict-native-example[]
        });
  }
  private EventProcessingResult doAggregateRawEventsInternal() {
    if (!this.clusterLockService.isLockOwner(AGGREGATION_LOCK_NAME)) {
      throw new IllegalStateException(
          "The cluster lock "
              + AGGREGATION_LOCK_NAME
              + " must be owned by the current thread and server");
    }

    if (!this.portalEventDimensionPopulator.isCheckedDimensions()) {
      // First time aggregation has happened, run populateDimensions to ensure enough dimension data
      // exists
      final boolean populatedDimensions = this.portalEventAggregationManager.populateDimensions();
      if (!populatedDimensions) {
        this.logger.warn(
            "Aborting raw event aggregation, populateDimensions returned false so the state of date/time dimensions is unknown");
        return null;
      }
    }

    // Flush any dimension creation before aggregation
    final EntityManager entityManager = this.getEntityManager();
    entityManager.flush();
    entityManager.setFlushMode(FlushModeType.COMMIT);

    final IEventAggregatorStatus eventAggregatorStatus =
        eventAggregationManagementDao.getEventAggregatorStatus(ProcessingType.AGGREGATION, true);

    // Update status with current server name
    final String serverName = this.portalInfoProvider.getUniqueServerName();
    final String previousServerName = eventAggregatorStatus.getServerName();
    if (previousServerName != null && !serverName.equals(previousServerName)) {
      this.logger.debug(
          "Last aggregation run on {} clearing all aggregation caches", previousServerName);
      final Session session = getEntityManager().unwrap(Session.class);
      final Cache cache = session.getSessionFactory().getCache();
      cache.evictEntityRegions();
    }

    eventAggregatorStatus.setServerName(serverName);

    // Calculate date range for aggregation
    DateTime lastAggregated = eventAggregatorStatus.getLastEventDate();
    if (lastAggregated == null) {
      lastAggregated = portalEventDao.getOldestPortalEventTimestamp();

      // No portal events to aggregate, skip aggregation
      if (lastAggregated == null) {
        return new EventProcessingResult(0, null, null, true);
      }

      // First time aggregation has run, initialize the CLEAN_UNCLOSED status to save catch-up time
      final IEventAggregatorStatus cleanUnclosedStatus =
          eventAggregationManagementDao.getEventAggregatorStatus(
              ProcessingType.CLEAN_UNCLOSED, true);
      AggregationIntervalInfo oldestMinuteInterval =
          this.intervalHelper.getIntervalInfo(AggregationInterval.MINUTE, lastAggregated);
      cleanUnclosedStatus.setLastEventDate(oldestMinuteInterval.getStart().minusMinutes(1));
      eventAggregationManagementDao.updateEventAggregatorStatus(cleanUnclosedStatus);
    }

    final DateTime newestEventTime =
        DateTime.now().minus(this.aggregationDelay).secondOfMinute().roundFloorCopy();

    final Thread currentThread = Thread.currentThread();
    final String currentName = currentThread.getName();
    final MutableInt events = new MutableInt();
    final MutableObject lastEventDate = new MutableObject(newestEventTime);

    boolean complete;
    try {
      currentThread.setName(currentName + "-" + lastAggregated + "_" + newestEventTime);

      logger.debug(
          "Starting aggregation of events between {} (inc) and {} (exc)",
          lastAggregated,
          newestEventTime);

      // Do aggregation, capturing the start and end dates
      eventAggregatorStatus.setLastStart(DateTime.now());

      complete =
          portalEventDao.aggregatePortalEvents(
              lastAggregated,
              newestEventTime,
              this.eventAggregationBatchSize,
              new AggregateEventsHandler(events, lastEventDate, eventAggregatorStatus));

      eventAggregatorStatus.setLastEventDate((DateTime) lastEventDate.getValue());
      eventAggregatorStatus.setLastEnd(DateTime.now());
    } finally {
      currentThread.setName(currentName);
    }

    // Store the results of the aggregation
    eventAggregationManagementDao.updateEventAggregatorStatus(eventAggregatorStatus);

    complete =
        complete
            && (this.eventAggregationBatchSize <= 0
                || events.intValue() < this.eventAggregationBatchSize);
    return new EventProcessingResult(
        events.intValue(), lastAggregated, eventAggregatorStatus.getLastEventDate(), complete);
  }
Ejemplo n.º 19
0
 @Override
 public long getNumberOfAssociations(Session session) {
   return getNumberOfAssociations(session.getSessionFactory());
 }
Ejemplo n.º 20
0
 @Override
 public long getNumberOfEntities(Session session) {
   return getNumberOfEntities(session.getSessionFactory());
 }
  @Test
  @FailureExpectedWithNewMetamodel(
      message =
          "ForeignKeyHelper.java:140 fails with org.hibernate.cfg.NotYetImplementedException: "
              + "No support yet for referenced join columns unless they correspond with columns bound for an attribute binding.")
  public void testPersistAndLoadUnderJta() throws Exception {
    Item item;
    SessionFactory sessionFactory = buildSessionFactory();
    try {
      UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction");
      ut.begin();
      try {
        Session session = sessionFactory.openSession();
        session.getTransaction().begin();
        item = new Item("anItem", "An item owned by someone");
        session.persist(item);
        session.getTransaction().commit();
        session.close();
      } catch (Exception e) {
        ut.setRollbackOnly();
        throw e;
      } finally {
        if (ut.getStatus() == Status.STATUS_ACTIVE) ut.commit();
        else ut.rollback();
      }

      ut = (UserTransaction) ctx.lookup("UserTransaction");
      ut.begin();
      try {
        Session session = sessionFactory.openSession();
        session.getTransaction().begin();
        Item found = (Item) session.load(Item.class, item.getId());
        Statistics stats = session.getSessionFactory().getStatistics();
        log.info(stats.toString());
        assertEquals(item.getDescription(), found.getDescription());
        assertEquals(0, stats.getSecondLevelCacheMissCount());
        assertEquals(1, stats.getSecondLevelCacheHitCount());
        session.delete(found);
        session.getTransaction().commit();
        session.close();
      } catch (Exception e) {
        ut.setRollbackOnly();
        throw e;
      } finally {
        if (ut.getStatus() == Status.STATUS_ACTIVE) ut.commit();
        else ut.rollback();
      }

      ut = (UserTransaction) ctx.lookup("UserTransaction");
      ut.begin();
      try {
        Session session = sessionFactory.openSession();
        session.getTransaction().begin();
        assertNull(session.get(Item.class, item.getId()));
        session.getTransaction().commit();
        session.close();
      } catch (Exception e) {
        ut.setRollbackOnly();
        throw e;
      } finally {
        if (ut.getStatus() == Status.STATUS_ACTIVE) ut.commit();
        else ut.rollback();
      }
    } finally {
      if (sessionFactory != null) sessionFactory.close();
    }
  }
 public void gera() {
   System.out.println("Gerando estàtisitcas");
   Session session = this.manager.unwrap(Session.class);
   this.estatisticas = session.getSessionFactory().getStatistics();
 }
Ejemplo n.º 23
0
 public SessionFactory getSessionFactory() {
   return session.getSessionFactory();
 }
  /* (non-Javadoc)
   * @see it.eng.qbe.export.IQueryRewriter#rewrite(java.lang.String)
   */
  public String rewrite(String query) {
    String sqlQuery = null;
    logger.debug("rewrite: HQL query to convert: " + query);

    Query hibQuery = session.createQuery(query);
    SessionFactory sessionFactory = session.getSessionFactory();
    SessionFactoryImplementor sessionFactoryImplementor =
        (SessionFactoryImplementor) sessionFactory;
    ASTQueryTranslatorFactory astQueryTranslatorFactory = new ASTQueryTranslatorFactory();
    QueryTranslator queryTranslator = null;

    Class[] parsTypes = null;

    Method createQueryTranslatorMethod = null;
    try {
      // Hibernate 3.0
      parsTypes = new Class[3];
      parsTypes[0] = String.class;
      parsTypes[1] = Map.class;
      parsTypes[2] = SessionFactoryImplementor.class;

      createQueryTranslatorMethod =
          astQueryTranslatorFactory.getClass().getMethod("createQueryTranslator", parsTypes);
      try {
        queryTranslator =
            (QueryTranslator)
                createQueryTranslatorMethod.invoke(
                    astQueryTranslatorFactory,
                    new Object[] {
                      hibQuery.getQueryString(), Collections.EMPTY_MAP, sessionFactoryImplementor
                    });
      } catch (Throwable e) {
        e.printStackTrace();
      }
    } catch (NoSuchMethodException e) {

      parsTypes = new Class[4];

      parsTypes[0] = String.class;
      parsTypes[1] = String.class;
      parsTypes[2] = Map.class;
      parsTypes[3] = SessionFactoryImplementor.class;

      try {
        createQueryTranslatorMethod =
            astQueryTranslatorFactory.getClass().getMethod("createQueryTranslator", parsTypes);

        if (createQueryTranslatorMethod != null) {
          try {
            queryTranslator =
                (QueryTranslator)
                    createQueryTranslatorMethod.invoke(
                        astQueryTranslatorFactory,
                        new Object[] {
                          String.valueOf(System.currentTimeMillis()),
                          hibQuery.getQueryString(),
                          Collections.EMPTY_MAP,
                          sessionFactoryImplementor
                        });
          } catch (Throwable t) {
            t.printStackTrace();
          }
        }
      } catch (NoSuchMethodException ex) {
        e.printStackTrace();
      }
    }

    queryTranslator.compile(new HashMap(), false);
    sqlQuery = queryTranslator.getSQLString();

    logger.debug("rewrite: generated SQL query: " + sqlQuery);

    return sqlQuery;
  }
  public static void main(String[] args) {
    HelperClassForUserCreation creator = new HelperClassForUserCreation();
    creator.createOrganizationAuthorAndIteration();
    Session session = ConnectionProvider.openSession();

    /*  Query iterations = session.createQuery("from Iteration where name='Unscheduled'");


    Iteration iteration = (Iteration) iterations.list().get(0);

    String [][] userStories =  {
            { "Log message geneation and saving in a separate log file", "log formate desc" },
            { "Formating of all modules per project (resuable components)", "log formate desc" },
            { "Hibernate mapping like task : Connection Pooling for hibernate and bi directional mapping call optimization", "log formate desc" },
            { "Hibernate adoption for annotations", "log formate desc" },
            { "Unit testing (JUnit) for business logic + hibernate testing", "log formate desc" },
            { "Unit Testing for JSP", "Desc"},
            { "Performance Testing", "Desc"},
            { "Tutorial Home page", "Desc"},
            { "Tutorial Sub page", "Desc"},
            { "Question entry page", "Desc"},
            { "Question entry edit and update", "Desc"},
            { "Maintaining the history of activities for all actions (by User, Project, Task, Iteration)", "User Story is for Task management module"},
            { "Overall report using some analyisis from previous task completed/inprogress", "Desc"},
            { "<b>Change log management for data base changes and incremental DB update</b>", "Desc"},
            { "<b>Upgrade, Backup and restore of data base from old database</b>", "Desc"},
            { "Finding of all topics and Question entry (50 per each topic)", "1. One use story can contain 10 tasks (i.e. 10 Task x 5 Question/Task x 3 Topics" +
            		"2. List down all topics, 3. Testing of each question readbility and speelling, formating"},
            { "Error management for all pages in Web application and logging in separate log file", "Desc"},
            { "Hosting of Website and finalization of steps", "Desc"},
            { "Google optimization in HTML file header for search topics", "Desc"},
            { "Blog entry and related questions to Q&A site", "Desc"},
            { "Interview question Topic separation and entry 20 questions per each topic", "Desc"},
            { "Performacne optimization of page and Enhance GUI implementation", "Desc"},
            { "Test matrix preparation and standadization of best practices in project with Task/Role separation", "Desc"},
            { "Separation of different modules and high level user stories and iterration separation", "Desc"},
            { "Standardizing the documentation for better maintanability", "Desc"},
            { "Increasing the Visitors for website and adverising in our and for our website", "Desc"},
            { "Learning of new topics and adding them to blog with analysis", "Desc"},
            { "Devleopment template preparation and knowledge sharing", "Desc"},
            { "Java Script validation of all pages", "Desc"},
            { "Better scripting and use of JQuert for enhanced GUI like calender", "Desc"},
            { "Separate schema mgt for each project", "Desc"},
            { "Pagination  (numbers of record per page)", "Desc"},

    };
    for (int i = 0; i < userStories.length; i++) {
        Query query = session.createQuery("from UserStory where name = '" + userStories[i][0] + "'");
        if (!query.list().isEmpty()) {
            System.out.println("+++++++++++ Already added " + query.list().get(0));
            continue;
        }
        UserStory story = new UserStory(userStories[i][0], userStories[i][1]);
        story.setAuthor(iteration.getAuthor());
        story.setCreationTime(new Date());
        story.setIteration(iteration);
        story.setPlanEstimate(3);
        story.setPriority((byte) Priority.High.getValue());
        session.save(story);
        // Create Task under each user story
        Task task = new Task("Sample Task" + i, "Sample Description");
        task.setAuthor(iteration.getAuthor());
        task.setUserStory(story);
        session.save(task);

        Bug bug = new Bug("Bug" + i, "Sample Bug Description");
        bug.setUserStory(story);

        PastInformation info = new PastInformation("first change", iteration.getAuthor());

        History history = new History();
        history.addInfo(info);
        bug.setHistory(history);
        bug.setUserStory(story);

        session.save(info);
        session.save(history);
        session.save(bug);
        System.out.println(">>>>>>>>> Successful creation of Story " + story);
    }*/
    // Populate One US with Task and Bugs

    ConnectionProvider.closeSessionAndDissconnect(session);
    session.getSessionFactory().close();
  }