public final String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
      throws HibernateException {
    String entityName = criteriaQuery.getEntityName(criteria, propertyName);
    String actualPropertyName = criteriaQuery.getPropertyName(propertyName);
    String sqlAlias = criteriaQuery.getSQLAlias(criteria, propertyName);

    SessionFactoryImplementor factory = criteriaQuery.getFactory();
    QueryableCollection collectionPersister =
        getQueryableCollection(entityName, actualPropertyName, factory);

    String[] collectionKeys = collectionPersister.getKeyColumnNames();
    String[] ownerKeys =
        ((Loadable) factory.getEntityPersister(entityName)).getIdentifierColumnNames();

    String innerSelect =
        "(select 1 from "
            + collectionPersister.getTableName()
            + " where "
            + new ConditionFragment()
                .setTableAlias(sqlAlias)
                .setCondition(ownerKeys, collectionKeys)
                .toFragmentString()
            + ")";

    return excludeEmpty() ? "exists " + innerSelect : "not exists " + innerSelect;
  }
  public void testXmlOverride() {
    AnnotationConfiguration config = new AnnotationConfiguration();
    config.addAnnotatedClass(Customer5.class);
    config.addAnnotatedClass(Order.class);
    config.addAnnotatedClass(Country.class);
    InputStream is =
        Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream("org/hibernate/test/annotations/fetchprofile/mappings.hbm.xml");
    config.addInputStream(is);
    SessionFactoryImplementor sessionImpl =
        (SessionFactoryImplementor)
            config.buildSessionFactory(serviceRegistryHolder.getServiceRegistry());

    assertTrue(
        "fetch profile not parsed properly",
        sessionImpl.containsFetchProfileDefinition("orders-profile"));

    // now the same with no xml
    config = new AnnotationConfiguration();
    config.addAnnotatedClass(Customer5.class);
    config.addAnnotatedClass(Order.class);
    config.addAnnotatedClass(Country.class);
    try {
      config.buildSessionFactory(serviceRegistryHolder.getServiceRegistry());
      fail();
    } catch (MappingException e) {
      log.trace("success");
    }
  }
예제 #3
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;
  }
 protected String generateLockString() {
   SessionFactoryImplementor factory = lockable.getFactory();
   Update update = new Update(factory.getDialect());
   update.setTableName(lockable.getRootTableName());
   update.addPrimaryKeyColumns(lockable.getRootTableIdentifierColumnNames());
   update.setVersionColumnName(lockable.getVersionColumnName());
   update.addColumn(lockable.getVersionColumnName());
   if (factory.getSettings().isCommentsEnabled()) {
     update.setComment(lockMode + " lock " + lockable.getEntityName());
   }
   return update.toStatementString();
 }
  /**
   * Attempts to load the entity from the second-level cache.
   *
   * @return The entity from the second-level cache, or null.
   * @throws HibernateException
   */
  protected Object loadFromSecondLevelCache(
      final LoadEvent event,
      final EntityPersister persister,
      final LoadEventListener.LoadType options)
      throws HibernateException {

    final SessionImplementor source = event.getSession();

    final boolean useCache =
        persister.hasCache()
            && source.getCacheMode().isGetEnabled()
            && event.getLockMode().lessThan(LockMode.READ);

    if (useCache) {

      final SessionFactoryImplementor factory = source.getFactory();

      final CacheKey ck =
          new CacheKey(
              event.getEntityId(),
              persister.getIdentifierType(),
              persister.getRootEntityName(),
              source.getEntityMode(),
              source.getFactory());
      Object ce = persister.getCache().get(ck, source.getTimestamp());

      if (factory.getStatistics().isStatisticsEnabled()) {
        if (ce == null) {
          factory
              .getStatisticsImplementor()
              .secondLevelCacheMiss(persister.getCache().getRegionName());
        } else {
          factory
              .getStatisticsImplementor()
              .secondLevelCacheHit(persister.getCache().getRegionName());
        }
      }

      if (ce != null) {

        CacheEntry entry = (CacheEntry) persister.getCacheEntryStructure().destructure(ce, factory);

        // Entity was found in second-level cache...
        return assembleCacheEntry(entry, event.getEntityId(), persister, event);
      }
    }

    return null;
  }
예제 #6
0
 protected String generateLockString() {
   SessionFactoryImplementor factory = lockable.getFactory();
   SimpleSelect select =
       new SimpleSelect(factory.getDialect())
           .setLockMode(lockMode)
           .setTableName(lockable.getRootTableName())
           .addColumn(lockable.getRootTableIdentifierColumnNames()[0])
           .addCondition(lockable.getRootTableIdentifierColumnNames(), "=?");
   if (lockable.isVersioned()) {
     select.addCondition(lockable.getVersionColumnName(), "=?");
   }
   if (factory.getSettings().isCommentsEnabled()) {
     select.setComment(lockMode + " lock " + lockable.getEntityName());
   }
   return select.toStatementString();
 }
  @Override
  protected void tearDown() throws Exception {
    if (sessionFactory != null) {
      sessionFactory.close();
    }

    super.tearDown();
  }
  public void testFetchProfileConfigured() {
    AnnotationConfiguration config = new AnnotationConfiguration();
    config.addAnnotatedClass(Customer.class);
    config.addAnnotatedClass(Order.class);
    config.addAnnotatedClass(SupportTickets.class);
    config.addAnnotatedClass(Country.class);
    SessionFactoryImplementor sessionImpl =
        (SessionFactoryImplementor)
            config.buildSessionFactory(serviceRegistryHolder.getServiceRegistry());

    assertTrue(
        "fetch profile not parsed properly",
        sessionImpl.containsFetchProfileDefinition("customer-with-orders"));
    assertFalse(
        "package info should not be parsed",
        sessionImpl.containsFetchProfileDefinition("package-profile-1"));
  }
  public void testPackageConfiguredFetchProfile() {
    AnnotationConfiguration config = new AnnotationConfiguration();
    config.addAnnotatedClass(Customer.class);
    config.addAnnotatedClass(Order.class);
    config.addAnnotatedClass(SupportTickets.class);
    config.addAnnotatedClass(Country.class);
    config.addPackage(Customer.class.getPackage().getName());
    SessionFactoryImplementor sessionImpl =
        (SessionFactoryImplementor)
            config.buildSessionFactory(serviceRegistryHolder.getServiceRegistry());

    assertTrue(
        "fetch profile not parsed properly",
        sessionImpl.containsFetchProfileDefinition("package-profile-1"));
    assertTrue(
        "fetch profile not parsed properly",
        sessionImpl.containsFetchProfileDefinition("package-profile-2"));
  }
 private String resolveToLiteralString(Type type) {
   try {
     LiteralType literalType = (LiteralType) type;
     Dialect dialect = factory.getDialect();
     return literalType.objectToSQLString(constantValue, dialect);
   } catch (Throwable t) {
     throw new QueryException(QueryTranslator.ERROR_CANNOT_FORMAT_LITERAL + constantExpression, t);
   }
 }
  /** @see LockingStrategy#lock */
  public void lock(
      Serializable id, Object version, Object object, int timeout, SessionImplementor session)
      throws StaleObjectStateException, JDBCException {
    if (!lockable.isVersioned()) {
      throw new HibernateException(
          "write locks via update not supported for non-versioned entities ["
              + lockable.getEntityName()
              + "]");
    }
    // todo : should we additionally check the current isolation mode explicitly?
    SessionFactoryImplementor factory = session.getFactory();
    try {
      PreparedStatement st = session.getBatcher().prepareSelectStatement(sql);
      try {
        lockable.getVersionType().nullSafeSet(st, version, 1, session);
        int offset = 2;

        lockable.getIdentifierType().nullSafeSet(st, id, offset, session);
        offset += lockable.getIdentifierType().getColumnSpan(factory);

        if (lockable.isVersioned()) {
          lockable.getVersionType().nullSafeSet(st, version, offset, session);
        }

        int affected = st.executeUpdate();
        if (affected < 0) {
          factory.getStatisticsImplementor().optimisticFailure(lockable.getEntityName());
          throw new StaleObjectStateException(lockable.getEntityName(), id);
        }

      } finally {
        session.getBatcher().closeStatement(st);
      }

    } catch (SQLException sqle) {
      throw session
          .getFactory()
          .getSQLExceptionHelper()
          .convert(
              sqle,
              "could not lock: " + MessageHelper.infoString(lockable, id, session.getFactory()),
              sql);
    }
  }
 private String getPathEntityName(String path) {
   Queryable persister = (Queryable) sessionFactory.getEntityPersister(rootEntityName);
   StringTokenizer tokens = new StringTokenizer(path, ".");
   String componentPath = "";
   while (tokens.hasMoreTokens()) {
     componentPath += tokens.nextToken();
     Type type = persister.toType(componentPath);
     if (type.isAssociationType()) {
       AssociationType atype = (AssociationType) type;
       persister =
           (Queryable)
               sessionFactory.getEntityPersister(atype.getAssociatedEntityName(sessionFactory));
       componentPath = "";
     } else if (type.isComponentType()) {
       componentPath += '.';
     } else {
       throw new QueryException("not an association: " + componentPath);
     }
   }
   return persister.getEntityName();
 }
예제 #13
0
 public OneToManyPersister(
     Collection collection,
     CollectionRegionAccessStrategy cacheAccessStrategy,
     Configuration cfg,
     SessionFactoryImplementor factory)
     throws MappingException, CacheException {
   super(collection, cacheAccessStrategy, cfg, factory);
   cascadeDeleteEnabled =
       collection.getKey().isCascadeDeleteEnabled()
           && factory.getDialect().supportsCascadeDelete();
   keyIsNullable = collection.getKey().isNullable();
   keyIsUpdateable = collection.getKey().isUpdateable();
 }
예제 #14
0
  /** @see LockingStrategy#lock */
  public void lock(Serializable id, Object version, Object object, SessionImplementor session)
      throws StaleObjectStateException, JDBCException {

    SessionFactoryImplementor factory = session.getFactory();
    try {
      PreparedStatement st = session.getBatcher().prepareSelectStatement(sql);
      try {
        lockable.getIdentifierType().nullSafeSet(st, id, 1, session);
        if (lockable.isVersioned()) {
          lockable
              .getVersionType()
              .nullSafeSet(
                  st, version, lockable.getIdentifierType().getColumnSpan(factory) + 1, session);
        }

        ResultSet rs = st.executeQuery();
        try {
          if (!rs.next()) {
            if (factory.getStatistics().isStatisticsEnabled()) {
              factory.getStatisticsImplementor().optimisticFailure(lockable.getEntityName());
            }
            throw new StaleObjectStateException(lockable.getEntityName(), id);
          }
        } finally {
          rs.close();
        }
      } finally {
        session.getBatcher().closeStatement(st);
      }

    } catch (SQLException sqle) {
      throw JDBCExceptionHelper.convert(
          session.getFactory().getSQLExceptionConverter(),
          sqle,
          "could not lock: " + MessageHelper.infoString(lockable, id, session.getFactory()),
          sql);
    }
  }
예제 #15
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;
  }
  protected QueryableCollection getQueryableCollection(
      String entityName, String propertyName, SessionFactoryImplementor factory)
      throws HibernateException {
    PropertyMapping ownerMapping = (PropertyMapping) factory.getEntityPersister(entityName);
    Type type = ownerMapping.toType(propertyName);
    if (!type.isCollectionType()) {
      throw new MappingException(
          "Property path ["
              + entityName
              + "."
              + propertyName
              + "] does not reference a collection");
    }

    String role = ((CollectionType) type).getRole();
    try {
      return (QueryableCollection) factory.getCollectionPersister(role);
    } catch (ClassCastException cce) {
      throw new QueryException("collection role is not queryable: " + role);
    } catch (Exception e) {
      throw new QueryException("collection role not found: " + role);
    }
  }
  public void testHiLoAlgorithm() {
    SessionImpl session = (SessionImpl) sessionFactory.openSession();
    session.beginTransaction();

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // initially sequence should be uninitialized
    assertEquals(0L, extractSequenceValue(session));

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // historically the hilo generators skipped the initial block of values;
    // 		so the first generated id value is maxlo + 1, here be 4
    Long generatedValue = (Long) generator.generate(session, null);
    assertEquals(1L, generatedValue.longValue());
    // which should also perform the first read on the sequence which should set it to its "start
    // with" value (1)
    assertEquals(1L, extractSequenceValue(session));

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    generatedValue = (Long) generator.generate(session, null);
    assertEquals(2L, generatedValue.longValue());
    assertEquals(2L, extractSequenceValue(session));

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    generatedValue = (Long) generator.generate(session, null);
    assertEquals(3L, generatedValue.longValue());
    assertEquals(3L, extractSequenceValue(session));

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    generatedValue = (Long) generator.generate(session, null);
    assertEquals(4L, generatedValue.longValue());
    assertEquals(4L, extractSequenceValue(session));

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    generatedValue = (Long) generator.generate(session, null);
    assertEquals(5L, generatedValue.longValue());
    assertEquals(5L, extractSequenceValue(session));

    session.getTransaction().commit();
    session.close();
  }
예제 #18
0
    /**
     * For each of the fields contained in this {@link Locks} object, parse out the type and the
     * field name and store those as the key and value in the "value" argument.
     */
    public void fillRelationships(SessionFactoryImplementor sfi, Map<String, Relationship> value) {

      final Type[] types = cm.getPropertyTypes();
      for (int t = 0; t < types.length; t++) {

        final Type type = types[t];
        final String name = type.getName();

        String to = null;
        Relationship field = null;
        if (type instanceof EntityType) {
          final EntityType entType = (EntityType) type;
          to = entType.getAssociatedEntityName();
          field = new Relationship(cm.getPropertyNames()[t], false);

        } else if (types[t] instanceof CollectionType) {
          final CollectionType colType = (CollectionType) types[t];
          final Type elemType = colType.getElementType(sfi);
          if (!elemType.isEntityType()) {
            continue; // The case for count maps and other primitives.
          }
          to = elemType.getName();

          int open = name.indexOf("(");
          int close = name.lastIndexOf(")");
          String role = name.substring(open + 1, close);
          int dot = role.lastIndexOf(".");
          field = new Relationship(role.substring(dot + 1), true);
        }

        if (to != null && field != null) {
          Map<String, ClassMetadata> m = sfi.getAllClassMetadata();
          for (Class<?> c : Impl.hierarchy(m, to)) {
            value.put(c.getName(), field);
          }
        }
      }
    }
 private PropertyMapping getPropertyMapping(String entityName) throws MappingException {
   return (PropertyMapping) sessionFactory.getEntityPersister(entityName);
 }
  private Object assembleCacheEntry(
      final CacheEntry entry,
      final Serializable id,
      final EntityPersister persister,
      final LoadEvent event)
      throws HibernateException {

    final Object optionalObject = event.getInstanceToLoad();
    final EventSource session = event.getSession();
    final SessionFactoryImplementor factory = session.getFactory();

    if (log.isTraceEnabled()) {
      log.trace(
          "assembling entity from second-level cache: "
              + MessageHelper.infoString(persister, id, factory));
    }

    EntityPersister subclassPersister = factory.getEntityPersister(entry.getSubclass());
    Object result =
        optionalObject == null ? session.instantiate(subclassPersister, id) : optionalObject;

    // make it circular-reference safe
    TwoPhaseLoad.addUninitializedCachedEntity(
        new EntityKey(id, subclassPersister, session.getEntityMode()),
        result,
        subclassPersister,
        LockMode.NONE,
        entry.areLazyPropertiesUnfetched(),
        entry.getVersion(),
        session);

    Type[] types = subclassPersister.getPropertyTypes();
    Object[] values =
        entry.assemble(
            result,
            id,
            subclassPersister,
            session.getInterceptor(),
            session); // intializes result by side-effect
    TypeFactory.deepCopy(
        values, types, subclassPersister.getPropertyUpdateability(), values, session);

    Object version = Versioning.getVersion(values, subclassPersister);
    if (log.isTraceEnabled()) log.trace("Cached Version: " + version);

    final PersistenceContext persistenceContext = session.getPersistenceContext();
    persistenceContext.addEntry(
        result,
        Status.MANAGED,
        values,
        null,
        id,
        version,
        LockMode.NONE,
        true,
        subclassPersister,
        false,
        entry.areLazyPropertiesUnfetched());
    subclassPersister.afterInitialize(result, entry.areLazyPropertiesUnfetched(), session);
    persistenceContext.initializeNonLazyCollections();
    // upgrade the lock if necessary:
    // lock(result, lockMode);

    // PostLoad is needed for EJB3
    // TODO: reuse the PostLoadEvent...
    PostLoadEvent postLoadEvent =
        new PostLoadEvent(session).setEntity(result).setId(id).setPersister(persister);
    PostLoadEventListener[] listeners = session.getListeners().getPostLoadEventListeners();
    for (int i = 0; i < listeners.length; i++) {
      listeners[i].onPostLoad(postLoadEvent);
    }

    return result;
  }
  public <T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass) {
    try {
      /*
       * Get the named query.
       * If the named query is a SQL query, get the expected returned type from the query definition
       * or its associated result set mapping
       * If the named query is a HQL query, use getReturnType()
       */
      org.hibernate.Query namedQuery = getSession().getNamedQuery(name);
      // TODO clean this up to avoid downcasting
      final SessionFactoryImplementor factoryImplementor =
          (SessionFactoryImplementor) entityManagerFactory.getSessionFactory();
      final NamedSQLQueryDefinition queryDefinition = factoryImplementor.getNamedSQLQuery(name);
      try {
        if (queryDefinition != null) {
          Class<?> actualReturnedClass;

          final NativeSQLQueryReturn[] queryReturns;
          if (queryDefinition.getQueryReturns() != null) {
            queryReturns = queryDefinition.getQueryReturns();
          } else if (queryDefinition.getResultSetRef() != null) {
            final ResultSetMappingDefinition rsMapping =
                factoryImplementor.getResultSetMapping(queryDefinition.getResultSetRef());
            queryReturns = rsMapping.getQueryReturns();
          } else {
            throw new AssertionFailure(
                "Unsupported named query model. Please report the bug in Hibernate EntityManager");
          }
          if (queryReturns.length > 1) {
            throw new IllegalArgumentException(
                "Cannot create TypedQuery for query with more than one return");
          }
          final NativeSQLQueryReturn nativeSQLQueryReturn = queryReturns[0];
          if (nativeSQLQueryReturn instanceof NativeSQLQueryRootReturn) {
            final String entityClassName =
                ((NativeSQLQueryRootReturn) nativeSQLQueryReturn).getReturnEntityName();
            try {
              actualReturnedClass =
                  ReflectHelper.classForName(entityClassName, AbstractEntityManagerImpl.class);
            } catch (ClassNotFoundException e) {
              throw new AssertionFailure(
                  "Unable to instantiate class declared on named native query: "
                      + name
                      + " "
                      + entityClassName);
            }
            if (!resultClass.isAssignableFrom(actualReturnedClass)) {
              throw buildIncompatibleException(resultClass, actualReturnedClass);
            }
          } else {
            // TODO support other NativeSQLQueryReturn type. For now let it go.
          }
        } else {
          if (namedQuery.getReturnTypes().length != 1) {
            throw new IllegalArgumentException(
                "Cannot create TypedQuery for query with more than one return");
          }
          if (!resultClass.isAssignableFrom(namedQuery.getReturnTypes()[0].getReturnedClass())) {
            throw buildIncompatibleException(
                resultClass, namedQuery.getReturnTypes()[0].getReturnedClass());
          }
        }
        return new QueryImpl<T>(namedQuery, this);
      } catch (HibernateException he) {
        throw convert(he);
      }
    } catch (MappingException e) {
      throw new IllegalArgumentException("Named query not found: " + name);
    }
  }