List of usage examples for org.hibernate.cfg Configuration addAnnotatedClass
@SuppressWarnings({ "unchecked" }) public Configuration addAnnotatedClass(Class annotatedClass)
From source file:com.aegeus.db.DbSessionFactory.java
License:Apache License
protected void build(DbIdentity identity, List<Class> pojoGroup) { Configuration cfg = new Configuration(); cfg.setProperty("hibernate.connection.driver", identity.getDriver()) .setProperty("hibernate.dialect", identity.getDialect()) .setProperty("hibernate.connection.url", identity.getUrl()) .setProperty("hibernate.connection.username", identity.getUsername()) .setProperty("hibernate.connection.password", identity.getPassword()) .setProperty("hibernate.connection.CharSet", "utf-8") .setProperty("hibernate.connection.characterEncoding", "utf-8") .setProperty("hibernate.connection.useUnicode", "true") .setProperty("current_session_context_class", "thread").setProperty("connection.pool_size", "4") .setProperty("hibernate.show_sql", "true"); for (Class pojo : pojoGroup) { cfg.addAnnotatedClass(pojo); }// ww w . ja v a 2 s . co m StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(); builder.applySettings(cfg.getProperties()); factory = cfg.buildSessionFactory(builder.build()); }
From source file:com.almuradev.backpack.backend.DatabaseManager.java
License:MIT License
private static void registerTables(Configuration configuration) { // Add tables here configuration.addAnnotatedClass(Backpacks.class); configuration.addAnnotatedClass(Slots.class); }
From source file:com.astonish.dropwizard.routing.hibernate.RoutingSessionFactoryFactory.java
License:Apache License
/** * Adds annotated persistent entities.// w w w .j av a2 s . c o m * @param configuration * the configuration * @param entities * the persistent entities */ private void addAnnotatedClasses(Configuration configuration, Iterable<Class<?>> entities) { final SortedSet<String> entityClasses = Sets.newTreeSet(); for (Class<?> klass : entities) { configuration.addAnnotatedClass(klass); entityClasses.add(klass.getCanonicalName()); } LOGGER.info("Entity classes: {}", entityClasses); }
From source file:com.autobizlogic.abl.logic.dynamic.Deployer.java
License:Open Source License
/** * Deploy a jar into a database for use by DatabaseClassManager. * @param props Should contain the required parameters: * <ul>/*from w w w. j av a 2 s . co m*/ * <li>either HIB_CFG_FILE (Hibernate config file path as a string) or * HIB_CFG as a Hibernate Configuration object * <li>PROJECT_NAME: the name of the project to deploy to (will be created if it does not exist) * <li>JAR_FILE_NAME: the path of the jar file to deploy, as a String * <li>EFFECTIVE_DATE: the date/time at which the new logic classes should take effect, * as a java.util.Date (optional) * </ul> * @return Null if everything went OK, otherwise a reason for the failure */ public static String deploy(Properties props) { Logger root = Logger.getRootLogger(); root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN))); Logger.getLogger("org.hibernate").setLevel(Level.WARN); Logger.getLogger("org.hibernate.tool.hbm2ddl").setLevel(Level.DEBUG); Logger.getLogger("org.hibernate.SQL").setLevel(Level.DEBUG); Logger.getLogger("org.hibernate.transaction").setLevel(Level.DEBUG); Configuration config; if (props.get(HIB_CFG) == null) { config = new Configuration(); File cfgFile = new File((String) props.get(HIB_CFG_FILE)); config.configure(cfgFile); } else config = (Configuration) props.get(HIB_CFG); if (config.getClassMapping(Project.class.getName()) == null) { config.addAnnotatedClass(Project.class); config.addAnnotatedClass(LogicFile.class); config.addAnnotatedClass(LogicFileLog.class); } SessionFactory sessFact = config.buildSessionFactory(); Session session = sessFact.getCurrentSession(); Transaction tx = session.beginTransaction(); Query query = session.createQuery("from Project where name = :name").setString("name", (String) props.get(PROJECT_NAME)); Project project = (Project) query.uniqueResult(); if (project == null) { project = new Project(); project.setName((String) props.get(PROJECT_NAME)); session.save(project); } LogicFile logicFile = new LogicFile(); String fileName = (String) props.get(JAR_FILE_NAME); String shortFileName = fileName; if (fileName.length() > 300) shortFileName = fileName.substring(0, 300); logicFile.setName(shortFileName); logicFile.setCreationDate(new Timestamp(System.currentTimeMillis())); File jarFile = new File((String) props.get(JAR_FILE_NAME)); try { FileInputStream inStr = new FileInputStream(fileName); Blob blob = session.getLobHelper().createBlob(inStr, jarFile.length()); logicFile.setContent(blob); } catch (Exception ex) { throw new RuntimeException("Error while storing jar file into database", ex); } Date effDate = (Date) props.get(EFFECTIVE_DATE); logicFile.setEffectiveDate(new Timestamp(effDate.getTime())); logicFile.setProject(project); session.save(logicFile); tx.commit(); sessFact.close(); return null; }
From source file:com.blazebit.persistence.integration.hibernate.Hibernate43Integrator.java
License:Apache License
@Override public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { Class<?> valuesEntity;//from w ww . j a v a 2s . c o m boolean registerValuesEntity = true; try { valuesEntity = Class.forName("com.blazebit.persistence.impl.function.entity.ValuesEntity"); } catch (ClassNotFoundException e) { throw new RuntimeException("Are you missing blaze-persistence-core-impl on the classpath?", e); } Iterator<PersistentClass> iter = configuration.getClassMappings(); while (iter.hasNext()) { PersistentClass clazz = iter.next(); Class<?> entityClass = clazz.getMappedClass(); if (entityClass != null && entityClass.isAnnotationPresent(CTE.class)) { clazz.getTable().setSubselect("select * from " + clazz.getJpaEntityName()); } } if (registerValuesEntity) { // Register values entity if wasn't found configuration.addAnnotatedClass(valuesEntity); configuration.buildMappings(); PersistentClass clazz = configuration.getClassMapping(valuesEntity.getName()); clazz.getTable().setSubselect("select * from " + clazz.getJpaEntityName()); } serviceRegistry.locateServiceBinding(PersisterClassResolver.class) .setService(new CustomPersisterClassResolver()); serviceRegistry.locateServiceBinding(Database.class) .setService(new SimpleDatabase(configuration.getTableMappings(), sessionFactory.getDialect(), new SimpleTableNameFormatter(), configuration.buildMapping())); }
From source file:com.blazebit.persistence.integration.hibernate.Hibernate4Integrator.java
License:Apache License
@Override public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { Class<?> valuesEntity;/*w ww . j av a 2 s .co m*/ boolean registerValuesEntity = true; try { valuesEntity = Class.forName("com.blazebit.persistence.impl.function.entity.ValuesEntity"); } catch (ClassNotFoundException e) { throw new RuntimeException("Are you missing blaze-persistence-core-impl on the classpath?", e); } Iterator<PersistentClass> iter = configuration.getClassMappings(); while (iter.hasNext()) { PersistentClass clazz = iter.next(); Class<?> entityClass = clazz.getMappedClass(); if (valuesEntity.equals(entityClass)) { registerValuesEntity = false; } if (entityClass != null && entityClass.isAnnotationPresent(CTE.class)) { clazz.getTable().setSubselect("select * from " + clazz.getJpaEntityName()); } } if (registerValuesEntity) { // Register values entity if wasn't found configuration.addAnnotatedClass(valuesEntity); configuration.buildMappings(); PersistentClass clazz = configuration.getClassMapping(valuesEntity.getName()); clazz.getTable().setSubselect("select * from " + clazz.getJpaEntityName()); } serviceRegistry.locateServiceBinding(PersisterClassResolver.class) .setService(new CustomPersisterClassResolver()); serviceRegistry.locateServiceBinding(Database.class) .setService(new SimpleDatabase(configuration.getTableMappings(), sessionFactory.getDialect(), new SimpleTableNameFormatter(), configuration.buildMapping())); }
From source file:com.brienwheeler.apps.schematool.SchemaToolBean.java
License:Open Source License
private Configuration determineHibernateConfiguration() throws MappingException, ClassNotFoundException, IOException { // Read in the bean definitions but don't go creating all the singletons, // because that causes creation of data sources and connections to database, etc. NonInitializingClassPathXmlApplicationContext context = new NonInitializingClassPathXmlApplicationContext( new String[] { emfContextLocation }); try {/* w ww .j a v a2 s .com*/ context.loadBeanDefinitions(); // Get well-known EntityManagerFactory bean definition by name BeanDefinition emfBeanDef = context.getBeanDefinition(emfContextBeanName); if (emfBeanDef == null) { throw new RuntimeException("no bean defined: " + emfContextBeanName); } // Get the name of the persistence unit for this EntityManagerFactory PropertyValue puNameProperty = emfBeanDef.getPropertyValues().getPropertyValue("persistenceUnitName"); if (puNameProperty == null || !(puNameProperty.getValue() instanceof TypedStringValue)) { throw new RuntimeException( "no property 'persistenceUnitName' defined on bean: " + emfContextBeanName); } String puName = ((TypedStringValue) puNameProperty.getValue()).getValue(); // Get the name of the persistence unit for this EntityManagerFactory PropertyValue pumProperty = emfBeanDef.getPropertyValues().getPropertyValue("persistenceUnitManager"); PersistenceUnitManager pum = null; if (pumProperty != null) { pum = createConfiguredPum(context, pumProperty); } else { pum = simulateDefaultPum(context, emfBeanDef); } // create the Hibernate configuration PersistenceUnitInfo pui = pum.obtainPersistenceUnitInfo(puName); Configuration configuration = new Configuration(); configuration.setProperties(pui.getProperties()); for (String className : pui.getManagedClassNames()) { configuration.addAnnotatedClass(Class.forName(className)); } return configuration; } finally { context.close(); } }
From source file:com.cgi.poc.dw.dao.HibernateUtil.java
public HibernateUtil() { try {/*w ww .j av a2s . c o m*/ File newConfiguration = new File(CONFIG_PATH); Yaml yaml = new Yaml(); InputStream is = new FileInputStream(newConfiguration); LinkedHashMap yamlParsers = (LinkedHashMap<String, ArrayList>) yaml.load(is); LinkedHashMap databaseCfg = (LinkedHashMap<String, ArrayList>) yamlParsers.get("database"); String driver = (String) databaseCfg.get("driverClass"); String dbUrl = (String) databaseCfg.get("url"); String userName = (String) databaseCfg.get("user"); String userPwd = (String) databaseCfg.get("password"); Configuration configuration = new Configuration(); // need to be able to read config file to get the uname/pwd for testing.. can't // use in memory DB b/c we need json, and geometry types which are not supported // by h2 configuration.setProperty("connection.driver_class", driver); configuration.setProperty("hibernate.connection.url", dbUrl); configuration.setProperty("hibernate.connection.username", userName); configuration.setProperty("hibernate.connection.password", userPwd); configuration.setProperty("hibernate.current_session_context_class", "thread"); configuration.addAnnotatedClass(User.class); configuration.addAnnotatedClass(FireEvent.class); configuration.addAnnotatedClass(EventEarthquake.class); configuration.addAnnotatedClass(EventWeather.class); configuration.addAnnotatedClass(EventFlood.class); configuration.addAnnotatedClass(EventHurricane.class); configuration.addAnnotatedClass(EventTsunami.class); configuration.addAnnotatedClass(EventVolcano.class); configuration.addAnnotatedClass(EventNotification.class); configuration.addAnnotatedClass(EventNotificationZipcode.class); configuration.addAnnotatedClass(EventNotificationUser.class); sessionFactory = configuration.buildSessionFactory(); openSession = sessionFactory.openSession(); Connection sqlConnection = ((SessionImpl) openSession).connection(); sessionFactory.getCurrentSession(); JdbcConnection conn = new JdbcConnection(sqlConnection); Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(conn); Liquibase liquibase = new Liquibase("migrations.xml", new ClassLoaderResourceAccessor(), database); String ctx = null; liquibase.update(ctx); } catch (Exception ex) { Logger.getLogger(HibernateUtil.class.getName()).log(Level.SEVERE, null, ex); System.exit(0); } }
From source file:com.corundumstudio.core.extensions.hibernate.BaseTest.java
License:Apache License
protected static void initHibernate() { Properties props = buildDatabaseConfiguration("db1"); Configuration cfg = new Configuration(); cfg.setProperty(Environment.GENERATE_STATISTICS, "true"); cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "create"); cfg.setProperty(AvailableSettings.CACHE_REGION_FACTORY, InfinispanRegionFactory.class.getName()); cfg.setProperty(InfinispanRegionFactory.INFINISPAN_CONFIG_RESOURCE_PROP, "infinispan.xml"); cfg.setProperty(AvailableSettings.QUERY_CACHE_FACTORY, DynamicQueryCacheFactory.class.getName()); cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true"); cfg.setProperty(Environment.USE_QUERY_CACHE, "true"); cfg.addAnnotatedClass(SimpleEntity.class); cfg.buildMappings();/*from ww w.j av a 2 s .c o m*/ ServiceRegistryBuilder sb = new ServiceRegistryBuilder(); ServiceRegistry serviceRegistry = sb.applySettings(props).buildServiceRegistry(); sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory(serviceRegistry); EventListenerRegistry registry = sessionFactory.getServiceRegistry() .getService(EventListenerRegistry.class); registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(queryCacheEntityListener); registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(queryCacheEntityListener); registry.getEventListenerGroup(EventType.POST_DELETE).appendListener(queryCacheEntityListener); }
From source file:com.dotosoft.dotoquiz.tools.util.HibernateUtil.java
License:Apache License
public static SessionFactory buildSessionFactory(Settings setting) { try {/* w ww. ja va 2s .c o m*/ Properties prop = new Properties(); prop.setProperty("hibernate.connection.driver_class", setting.getConfiguration().getConnection().getDriverClass()); prop.setProperty("hibernate.connection.url", setting.getConfiguration().getConnection().getUrl()); prop.setProperty("hibernate.connection.username", setting.getConfiguration().getConnection().getUser()); prop.setProperty("hibernate.connection.password", setting.getConfiguration().getConnection().getPassword()); prop.setProperty("hibernate.connection.pool_size", String.valueOf(setting.getConfiguration().getConnection().getPoolSize())); prop.setProperty("hibernate.dialect", setting.getConfiguration().getDialect()); prop.setProperty("hibernate.hbm2ddl.auto", setting.getConfiguration().getHbm2ddl()); prop.setProperty("hibernate.show_sql", setting.getConfiguration().getShowSQL()); Configuration annotationConfig = new Configuration().addProperties(prop); for (String packageMap : setting.getConfiguration().getMappingPackages()) { annotationConfig.addPackage(packageMap); } for (String classMap : setting.getConfiguration().getMappingClasses()) { annotationConfig.addAnnotatedClass(Class.forName(classMap)); } StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder() .applySettings(annotationConfig.getProperties()); sessionFactory = annotationConfig.buildSessionFactory(ssrb.build()); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } return sessionFactory; }