Package org.hibernate.ejb

Examples of org.hibernate.ejb.Ejb3Configuration$Ejb3EntityNotFoundDelegate


  private Ejb3Configuration buildConfiguration(SharedCacheMode mode) {
    Properties properties = new Properties();
    properties.put( AvailableSettings.SHARED_CACHE_MODE, mode );
    properties.put( Environment.CACHE_REGION_FACTORY, CustomRegionFactory.class.getName() );
    Ejb3Configuration config = new Ejb3Configuration();
    config.setProperties( properties );
    config.addAnnotatedClass( ExplicitlyCacheableEntity.class );
    config.addAnnotatedClass( ExplicitlyNonCacheableEntity.class );
    config.addAnnotatedClass( NoCacheableAnnotationEntity.class );
    config.buildMappings();
    return config;
  }
View Full Code Here


            final String dataSource = Play.configuration.getProperty("hibernate.connection.datasource");
            if (StringUtils.isEmpty(dataSource) && DB.datasource == null) {
                throw new JPAException("Cannot start a JPA manager without a properly configured database", new NullPointerException("No datasource configured"));
            }

            Ejb3Configuration cfg = new Ejb3Configuration();

            if (DB.datasource != null) {
                cfg.setDataSource(DB.datasource);
            }

            if (!Play.configuration.getProperty("jpa.ddl", Play.mode.isDev() ? "update" : "none").equals("none")) {
                cfg.setProperty("hibernate.hbm2ddl.auto", Play.configuration.getProperty("jpa.ddl", "update"));
            }

            cfg.setProperty("hibernate.dialect", getDefaultDialect(Play.configuration.getProperty("db.driver")));
            cfg.setProperty("javax.persistence.transaction", "RESOURCE_LOCAL");

            // Explicit SAVE for JPABase is implemented here
            // ~~~~~~
            // We've hacked the org.hibernate.event.def.AbstractFlushingEventListener line 271, to flush collection update,remove,recreation
            // only if the owner will be saved.
            // As is:
            // if (session.getInterceptor().onCollectionUpdate(coll, ce.getLoadedKey())) {
            //      actionQueue.addAction(...);
            // }
            //
            // This is really hacky. We should move to something better than Hibernate like EBEAN
            cfg.setInterceptor(new EmptyInterceptor() {

                @Override
                public int[] findDirty(Object o, Serializable id, Object[] arg2, Object[] arg3, String[] arg4, Type[] arg5) {
                    if (o instanceof JPABase && !((JPABase) o).willBeSaved) {
                        return new int[0];
                    }
                    return null;
                }

                @Override
                public boolean onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
                    if (collection instanceof PersistentCollection) {
                        Object o = ((PersistentCollection) collection).getOwner();
                        if (o instanceof JPABase) {
                            return ((JPABase) o).willBeSaved;
                        }
                    } else {
                        System.out.println("HOO: Case not handled !!!");
                    }
                    return super.onCollectionUpdate(collection, key);
                }

                @Override
                public boolean onCollectionRecreate(Object collection, Serializable key) throws CallbackException {
                    if (collection instanceof PersistentCollection) {
                        Object o = ((PersistentCollection) collection).getOwner();
                        if (o instanceof JPABase) {
                            return ((JPABase) o).willBeSaved;
                        }
                    } else {
                        System.out.println("HOO: Case not handled !!!");
                    }
                    return super.onCollectionRecreate(collection, key);
                }

                @Override
                public boolean onCollectionRemove(Object collection, Serializable key) throws CallbackException {
                    if (collection instanceof PersistentCollection) {
                        Object o = ((PersistentCollection) collection).getOwner();
                        if (o instanceof JPABase) {
                            return ((JPABase) o).willBeSaved;
                        }
                    } else {
                        System.out.println("HOO: Case not handled !!!");
                    }
                    return super.onCollectionRemove(collection, key);
                }
            });
            if (Play.configuration.getProperty("jpa.debugSQL", "false").equals("true")) {
                org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.ALL);
            } else {
                org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.OFF);
            }
            // inject additional  hibernate.* settings declared in Play! configuration
            cfg.addProperties((Properties) Utils.Maps.filterMap(Play.configuration, "^hibernate\\..*"));

            try {
                Field field = cfg.getClass().getDeclaredField("overridenClassLoader");
                field.setAccessible(true);
                field.set(cfg, Play.classloader);
            } catch (Exception e) {
                Logger.error(e, "Error trying to override the hibernate classLoader (new hibernate version ???)");
            }
            for (Class<?> clazz : classes) {
                if (clazz.isAnnotationPresent(Entity.class)) {
                    cfg.addAnnotatedClass(clazz);
                    Logger.trace("JPA Model : %s", clazz);
                }
            }
            String[] moreEntities = Play.configuration.getProperty("jpa.entities", "").split(", ");
            for (String entity : moreEntities) {
                if (entity.trim().equals("")) {
                    continue;
                }
                try {
                    cfg.addAnnotatedClass(Play.classloader.loadClass(entity));
                } catch (Exception e) {
                    Logger.warn("JPA -> Entity not found: %s", entity);
                }
            }
            for (ApplicationClass applicationClass : Play.classes.all()) {
                if (applicationClass.isClass() || applicationClass.javaPackage == null) {
                    continue;
                }
                Package p = applicationClass.javaPackage;
                Logger.info("JPA -> Adding package: %s", p.getName());
                cfg.addPackage(p.getName());
            }
            String mappingFile = Play.configuration.getProperty("jpa.mapping-file", "");
            if (mappingFile != null && mappingFile.length() > 0) {
                cfg.addResource(mappingFile);
            }
            Logger.trace("Initializing JPA ...");
            try {
                JPA.entityManagerFactory = cfg.buildEntityManagerFactory();
            } catch (PersistenceException e) {
                throw new JPAException(e.getMessage(), e.getCause() != null ? e.getCause() : e);
            }
            JPQL.instance = new JPQL();
        }
View Full Code Here

        assertEquals("Wrong title", "Refactoring: Improving the Design of Existing Code", books.get(0).getTitle());
    }


    private void initHibernate() {
        Ejb3Configuration config = new Ejb3Configuration();
        config.configure("hibernate-search-example", new HashMap());
        emf = config.buildEntityManagerFactory();
        em = emf.createEntityManager();
    }
View Full Code Here

    assertEquals( "Wrong title", "Refactoring: Improving the Design of Existing Code", books.get( 0 ).getTitle() );
  }


  private void initHibernate() {
    Ejb3Configuration config = new Ejb3Configuration();
    config.configure( "hibernate-search-example", new HashMap() );
    emf = config.buildEntityManagerFactory();
    em = emf.createEntityManager();
  }
View Full Code Here

    protected PersistenceUnitInfo persistenceUnitInfo;

    public Ejb3Configuration getConfiguration() {
        synchronized(this) {
            if (configuration == null) {
                Ejb3Configuration temp = new Ejb3Configuration();
                String previousValue = persistenceUnitInfo.getProperties().getProperty("hibernate.hbm2ddl.auto");
                persistenceUnitInfo.getProperties().setProperty("hibernate.hbm2ddl.auto", "none");
                configuration = temp.configure(persistenceUnitInfo, new HashMap());
                configuration.getHibernateConfiguration().buildSessionFactory();
                if (previousValue != null) {
                    persistenceUnitInfo.getProperties().setProperty("hibernate.hbm2ddl.auto", previousValue);
                }
            }
View Full Code Here

            final String dataSource = Play.configuration.getProperty("hibernate.connection.datasource");
            if (StringUtils.isEmpty(dataSource) && DB.datasource == null) {
                throw new JPAException("Cannot start a JPA manager without a properly configured database", new NullPointerException("No datasource configured"));
            }

            Ejb3Configuration cfg = new Ejb3Configuration();

            if (DB.datasource != null) {
                cfg.setDataSource(DB.datasource);
            }

            if (!Play.configuration.getProperty("jpa.ddl", Play.mode.isDev() ? "update" : "none").equals("none")) {
                cfg.setProperty("hibernate.hbm2ddl.auto", Play.configuration.getProperty("jpa.ddl", "update"));
            }

            cfg.setProperty("hibernate.dialect", getDefaultDialect(Play.configuration.getProperty("db.driver")));
            cfg.setProperty("javax.persistence.transaction", "RESOURCE_LOCAL");

            // Explicit SAVE for JPABase is implemented here
            // ~~~~~~
            // We've hacked the org.hibernate.event.def.AbstractFlushingEventListener line 271, to flush collection update,remove,recreation
            // only if the owner will be saved.
            // As is:
            // if (session.getInterceptor().onCollectionUpdate(coll, ce.getLoadedKey())) {
            //      actionQueue.addAction(...);
            // }
            //
            // This is really hacky. We should move to something better than Hibernate like EBEAN
            cfg.setInterceptor(new EmptyInterceptor() {

                @Override
                public int[] findDirty(Object o, Serializable id, Object[] arg2, Object[] arg3, String[] arg4, Type[] arg5) {
                    if (o instanceof JPABase && !((JPABase) o).willBeSaved) {
                        return new int[0];
                    }
                    return null;
                }

                @Override
                public boolean onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
                    if (collection instanceof PersistentCollection) {
                        Object o = ((PersistentCollection) collection).getOwner();
                        if (o instanceof JPABase) {
                            return ((JPABase) o).willBeSaved;
                        }
                    } else {
                        System.out.println("HOO: Case not handled !!!");
                    }
                    return super.onCollectionUpdate(collection, key);
                }

                @Override
                public boolean onCollectionRecreate(Object collection, Serializable key) throws CallbackException {
                    if (collection instanceof PersistentCollection) {
                        Object o = ((PersistentCollection) collection).getOwner();
                        if (o instanceof JPABase) {
                            return ((JPABase) o).willBeSaved;
                        }
                    } else {
                        System.out.println("HOO: Case not handled !!!");
                    }
                    return super.onCollectionRecreate(collection, key);
                }

                @Override
                public boolean onCollectionRemove(Object collection, Serializable key) throws CallbackException {
                    if (collection instanceof PersistentCollection) {
                        Object o = ((PersistentCollection) collection).getOwner();
                        if (o instanceof JPABase) {
                            return ((JPABase) o).willBeSaved;
                        }
                    } else {
                        System.out.println("HOO: Case not handled !!!");
                    }
                    return super.onCollectionRemove(collection, key);
                }
            });
            if (Play.configuration.getProperty("jpa.debugSQL", "false").equals("true")) {
                org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.ALL);
            } else {
                org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.OFF);
            }
            // inject additional  hibernate.* settings declared in Play! configuration
            cfg.addProperties((Properties) Utils.Maps.filterMap(Play.configuration, "^hibernate\\..*"));

            try {
                Field field = cfg.getClass().getDeclaredField("overridenClassLoader");
                field.setAccessible(true);
                field.set(cfg, Play.classloader);
            } catch (Exception e) {
                Logger.error(e, "Error trying to override the hibernate classLoader (new hibernate version ???)");
            }
            for (Class<?> clazz : classes) {
                if (clazz.isAnnotationPresent(Entity.class)) {
                    cfg.addAnnotatedClass(clazz);
                    if (Logger.isTraceEnabled()) {
                        Logger.trace("JPA Model : %s", clazz);
                    }
                }
            }
            String[] moreEntities = Play.configuration.getProperty("jpa.entities", "").split(", ");
            for (String entity : moreEntities) {
                if (entity.trim().equals("")) {
                    continue;
                }
                try {
                    cfg.addAnnotatedClass(Play.classloader.loadClass(entity));
                } catch (Exception e) {
                    Logger.warn("JPA -> Entity not found: %s", entity);
                }
            }
            for (ApplicationClass applicationClass : Play.classes.all()) {
                if (applicationClass.isClass() || applicationClass.javaPackage == null) {
                    continue;
                }
                Package p = applicationClass.javaPackage;
                Logger.info("JPA -> Adding package: %s", p.getName());
                cfg.addPackage(p.getName());
            }
            String mappingFile = Play.configuration.getProperty("jpa.mapping-file", "");
            if (mappingFile != null && mappingFile.length() > 0) {
                cfg.addResource(mappingFile);
            }
            if (Logger.isTraceEnabled()) {
                Logger.trace("Initializing JPA ...");
            }
            try {
                JPA.entityManagerFactory = cfg.buildEntityManagerFactory();
            } catch (PersistenceException e) {
                throw new JPAException(e.getMessage(), e.getCause() != null ? e.getCause() : e);
            }
            JPQL.instance = new JPQL();
        }
View Full Code Here

    /**
     *
     */
    @BeforeClass
    public static void initializeDerbyHibernate() {
        final Ejb3Configuration configuration = DerbyHibernateUtil.configureDerbyHibernateJpa();
        ENTITY_MANAGER_FACTORY.set(configuration.buildEntityManagerFactory());
    }
View Full Code Here

        properties.put("hibernate.connection.url", JDBC_DERBY_URL);
        properties.put("hibernate.connection.pool_size", "5");
        properties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
        properties.put("hibernate.hbm2ddl.auto", "create-drop");

        final Ejb3Configuration cfg = new Ejb3Configuration();
        cfg.configure("test", properties);
        for (final Class<?> clazz : classes) {
            cfg.addAnnotatedClass(clazz);
        }
        return cfg;
    }
View Full Code Here

    /**
     * @param classes
     *        the annotated classes
     */
    public HibernatePersistenceContext(final Class<?>... classes) {
        final Ejb3Configuration cfg = DerbyHibernateUtil.configureDerbyHibernateJpa(classes);
        entityManagerFactory = cfg.buildEntityManagerFactory();
        entityManager = entityManagerFactory.createEntityManager();
    }
View Full Code Here

        assert rootNodeUuid != null;
        assert rootUuid != null;
        EntityManager entityManager = null;
        if (entityManagerFactory == null || !entityManagerFactory.isOpen()) {
            // Create the JPA EntityManagerFactory by programmatically configuring Hibernate Entity Manager ...
            Ejb3Configuration configurator = new Ejb3Configuration();

            // Configure the entity classes ...
            configurator.addAnnotatedClass(StoreOptionEntity.class);
            if (model != null) model.configure(configurator);

            // Configure additional properties, which may be overridden by subclasses ...
            configure(configurator);

            // Now set the mandatory information, overwriting anything that the subclasses may have tried ...
            if (this.dataSource == null && this.dataSourceJndiName != null) {
                // Try to load the DataSource from JNDI ...
                try {
                    Context context = new InitialContext();
                    dataSource = (DataSource)context.lookup(this.dataSourceJndiName);
                } catch (Throwable t) {
                    Logger.getLogger(getClass())
                          .error(t, JpaConnectorI18n.errorFindingDataSourceInJndi, name, dataSourceJndiName);
                }
            }

            if (this.dataSource != null) {
                // Set the data source ...
                configurator.setDataSource(this.dataSource);
            } else {
                // Set the context class loader, so that the driver could be found ...
                if (this.repositoryContext != null && this.driverClassloaderName != null) {
                    try {
                        ExecutionContext context = this.repositoryContext.getExecutionContext();
                        ClassLoader loader = context.getClassLoader(this.driverClassloaderName);
                        if (loader != null) {
                            Thread.currentThread().setContextClassLoader(loader);
                        }
                    } catch (Throwable t) {
                        I18n msg = JpaConnectorI18n.errorSettingContextClassLoader;
                        Logger.getLogger(getClass()).error(t, msg, name, driverClassloaderName);
                    }
                }
                // Set the connection properties ...
                setProperty(configurator, "hibernate.dialect", this.dialect);
                setProperty(configurator, "hibernate.connection.driver_class", this.driverClassName);
                setProperty(configurator, "hibernate.connection.username", this.username);
                setProperty(configurator, "hibernate.connection.password", this.password);
                setProperty(configurator, "hibernate.connection.url", this.url);
                setProperty(configurator, "hibernate.connection.max_fetch_depth", DEFAULT_MAXIMUM_FETCH_DEPTH);
                setProperty(configurator, "hibernate.connection.pool_size", 0); // don't use the built-in pool
            }

            entityManagerFactory = configurator.buildEntityManagerFactory();

            // Establish a connection and obtain the store options...
            entityManager = entityManagerFactory.createEntityManager();

            // Find and update/set the root node's UUID ...
            StoreOptions options = new StoreOptions(entityManager);
            UUID actualUuid = options.getRootNodeUuid();
            if (actualUuid != null) {
                this.setRootNodeUuid(actualUuid.toString());
            } else {
                options.setRootNodeUuid(this.rootUuid);
            }

            // Find or set the type of model that will be used.
            String actualModelName = options.getModelName();
            if (actualModelName == null) {
                // This is a new store, so set to the specified model ...
                if (model == null) setModel(Models.DEFAULT.getName());
                assert model != null;
                options.setModelName(model);
            } else {
                try {
                    setModel(actualModelName);
                } catch (Throwable e) {
                    // The actual model name doesn't match what's available in the software ...
                    entityManagerFactory.close();
                    String msg = JpaConnectorI18n.existingStoreSpecifiesUnknownModel.text(name, actualModelName);
                    throw new RepositorySourceException(msg);
                }
            }
            entityManagerFactory.close();

            // Now, create another entity manager with the classes from the correct model
            model.configure(configurator);
            entityManagerFactory = configurator.buildEntityManagerFactory();
            entityManager = entityManagerFactory.createEntityManager();
        }
        if (entityManager == null) {
            entityManager = entityManagerFactory.createEntityManager();
        }
View Full Code Here

TOP

Related Classes of org.hibernate.ejb.Ejb3Configuration$Ejb3EntityNotFoundDelegate

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.