List of usage examples for org.hibernate.tool.hbm2ddl SchemaExport create
public void create(EnumSet<TargetType> targetTypes, Metadata metadata)
From source file:com.brienwheeler.apps.schematool.SchemaToolBean.java
License:Open Source License
public void afterPropertiesSet() throws Exception { try {//from www . j av a 2 s . co m // set based on default values in schematool properties file if not already set PropertyPlaceholderConfigurer.setProperty(emfPersistenceLocationsPropName, emfPersistenceLocationsPropValue); Configuration configuration = determineHibernateConfiguration(); Settings settings = null; if (exec || mode == Mode.UPDATE) { ClassPathXmlApplicationContext newContext = new SmartClassPathXmlApplicationContext( emfContextLocation); try { // get a reference to the factory bean, don't have it create a new EntityManager LocalContainerEntityManagerFactoryBean factoryBean = newContext .getBean("&" + emfContextBeanName, LocalContainerEntityManagerFactoryBean.class); SettingsFactory settingsFactory = new InjectedDataSourceSettingsFactory( factoryBean.getDataSource()); settings = settingsFactory.buildSettings(new Properties()); } finally { newContext.close(); } } if (mode == Mode.UPDATE) { SchemaUpdate update = new SchemaUpdate(configuration, settings); update.execute(true, exec); } else { SchemaExport export = exec ? new SchemaExport(configuration, settings) : new SchemaExport(configuration); export.create(true, exec); } } catch (Exception e) { log.error("Error running SchemaTool", e); throw e; } }
From source file:com.devnexus.ting.core.dao.hibernate.SystemDaoHibernate.java
License:Apache License
@Override public void createDatabase(boolean outputOnly, String dialect) { final Map<String, Object> propertyMap = fb.getJpaPropertyMap(); final Map<String, Object> localPropertyMap = new HashMap<>(propertyMap); if (dialect != null) { localPropertyMap.put("hibernate.dialect", dialect); }// w w w . j a v a2 s . co m final MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder() .applySetting("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect") .applySetting("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName()) .applySetting("hibernate.implicit_naming_strategy", DevNexusSpringImplicitNamingStrategy.class.getName()) .applySettings(localPropertyMap).build()); for (Class<?> clazz : PersistenceConfig.getAnnotatedPersistenceClasses()) { metadata.addAnnotatedClass(clazz); } final SchemaExport export; try { export = new SchemaExport((MetadataImplementor) metadata.buildMetadata(), dataSource.getConnection()); } catch (HibernateException | SQLException e) { throw new IllegalStateException(e); } export.create(true, !outputOnly); }
From source file:com.esales.util.GeradorTabela.java
public static void main(String[] args) { AnnotationConfiguration configuracao = new AnnotationConfiguration(); configuracao.addAnnotatedClass(Categoria.class); SchemaExport export = new SchemaExport(configuracao); export.create(true, false); }
From source file:com.fiveamsolutions.nci.commons.test.AbstractHibernateTestCase.java
License:Open Source License
/** * In JUnit3x you would normally override the setUp() and add your own functionality locally however, in JUnit4 to * override simply define your method and give it the <code>@Before annotation</code>. Doing so will cause that * method to be invoked after the parent class's setUp(). *//*from w ww. jav a 2 s.c o m*/ @SuppressWarnings("unchecked") @Before public final void setUp() { Transaction tx = HibernateUtil.getHibernateHelper().beginTransaction(); SchemaExport se = new SchemaExport(HibernateUtil.getHibernateHelper().getConfiguration()); se.drop(false, true); se.create(false, true); tx.commit(); // clean up the hibernate second level cache between runs SessionFactory sf = getCurrentSession().getSessionFactory(); Map<?, EntityPersister> classMetadata = sf.getAllClassMetadata(); for (EntityPersister ep : classMetadata.values()) { if (ep.hasCache()) { sf.evictEntity(ep.getCacheAccessStrategy().getRegion().getName()); } } Map<?, AbstractCollectionPersister> collMetadata = sf.getAllCollectionMetadata(); for (AbstractCollectionPersister acp : collMetadata.values()) { if (acp.hasCache()) { sf.evictCollection(acp.getCacheAccessStrategy().getRegion().getName()); } } transaction = HibernateUtil.getHibernateHelper().beginTransaction(); }
From source file:com.fiveamsolutions.nci.commons.util.HibernateHelperTest.java
License:Open Source License
@Before final public void initDbIfNeeded() throws HibernateException { initHelper();/*from ww w. ja v a 2 s. c o m*/ hh.openAndBindSession(); Transaction tx = hh.beginTransaction(); SchemaExport se = new SchemaExport(hh.getConfiguration()); se.drop(false, true); se.create(false, true); tx.commit(); hh.unbindAndCleanupSession(); }
From source file:com.floreantpos.util.DatabaseUtil.java
License:Open Source License
public static boolean createDatabase(String connectionString, String hibernateDialect, String hibernateConnectionDriverClass, String user, String password, boolean exportSampleData) { try {/*from www . ja v a 2 s. c o m*/ Configuration configuration = _RootDAO.getNewConfiguration(null); configuration = configuration.setProperty("hibernate.dialect", hibernateDialect); configuration = configuration.setProperty("hibernate.connection.driver_class", hibernateConnectionDriverClass); configuration = configuration.setProperty("hibernate.connection.url", connectionString); configuration = configuration.setProperty("hibernate.connection.username", user); configuration = configuration.setProperty("hibernate.connection.password", password); configuration = configuration.setProperty("hibernate.hbm2ddl.auto", "create"); configuration = configuration.setProperty("hibernate.c3p0.checkoutTimeout", "0"); //$NON-NLS-1$ //$NON-NLS-2$ SchemaExport schemaExport = new SchemaExport(configuration); schemaExport.create(true, true); _RootDAO.initialize(); Restaurant restaurant = new Restaurant(); restaurant.setId(Integer.valueOf(1)); restaurant.setName("Sample Restaurant"); restaurant.setAddressLine1("Somewhere"); restaurant.setTelephone("+0123456789"); RestaurantDAO.getInstance().saveOrUpdate(restaurant); Tax tax = new Tax(); tax.setName("US"); tax.setRate(Double.valueOf(6)); TaxDAO.getInstance().saveOrUpdate(tax); Shift shift = new Shift(); shift.setName(com.floreantpos.POSConstants.GENERAL); java.util.Date shiftStartTime = ShiftUtil.buildShiftStartTime(0, 0, 0, 11, 59, 1); java.util.Date shiftEndTime = ShiftUtil.buildShiftEndTime(0, 0, 0, 11, 59, 1); shift.setStartTime(shiftStartTime); shift.setEndTime(shiftEndTime); long length = Math.abs(shiftStartTime.getTime() - shiftEndTime.getTime()); shift.setShiftLength(Long.valueOf(length)); ShiftDAO.getInstance().saveOrUpdate(shift); UserType administrator = new UserType(); administrator.setName(com.floreantpos.POSConstants.ADMINISTRATOR); administrator.setPermissions(new HashSet<UserPermission>(Arrays.asList(UserPermission.permissions))); UserTypeDAO.getInstance().saveOrUpdate(administrator); UserType manager = new UserType(); manager.setName(com.floreantpos.POSConstants.MANAGER); manager.setPermissions(new HashSet<UserPermission>(Arrays.asList(UserPermission.permissions))); UserTypeDAO.getInstance().saveOrUpdate(manager); UserType cashier = new UserType(); cashier.setName(com.floreantpos.POSConstants.CASHIER); cashier.setPermissions(new HashSet<UserPermission>( Arrays.asList(UserPermission.CREATE_TICKET, UserPermission.SETTLE_TICKET, UserPermission.SPLIT_TICKET, UserPermission.VIEW_ALL_OPEN_TICKETS))); UserTypeDAO.getInstance().saveOrUpdate(cashier); UserType server = new UserType(); server.setName("SR. CASHIER"); server.setPermissions(new HashSet<UserPermission>(Arrays.asList(UserPermission.CREATE_TICKET, UserPermission.SETTLE_TICKET, UserPermission.SPLIT_TICKET))); //server.setTest(Arrays.asList(OrderType.BAR_TAB)); UserTypeDAO.getInstance().saveOrUpdate(server); User administratorUser = new User(); administratorUser.setUserId(123); administratorUser.setSsn("123"); administratorUser.setPassword("1111"); administratorUser.setFirstName("Admin"); administratorUser.setLastName("System"); administratorUser.setType(administrator); administratorUser.setActive(true); UserDAO dao = new UserDAO(); dao.saveOrUpdate(administratorUser); User managerUser = new User(); managerUser.setUserId(124); managerUser.setSsn("124"); managerUser.setPassword("2222"); managerUser.setFirstName("Lisa"); managerUser.setLastName("Carol"); managerUser.setType(manager); managerUser.setActive(true); dao.saveOrUpdate(managerUser); User cashierUser = new User(); cashierUser.setUserId(125); cashierUser.setSsn("125"); cashierUser.setPassword("3333"); cashierUser.setFirstName("Janet"); cashierUser.setLastName("Ann"); cashierUser.setType(cashier); cashierUser.setActive(true); dao.saveOrUpdate(cashierUser); User serverUser = new User(); serverUser.setUserId(126); serverUser.setSsn("126"); serverUser.setPassword("7777"); serverUser.setFirstName("John"); serverUser.setLastName("Doe"); serverUser.setType(server); serverUser.setActive(true); dao.saveOrUpdate(serverUser); User driverUser = new User(); driverUser.setUserId(127); driverUser.setSsn("127"); driverUser.setPassword("8888"); driverUser.setFirstName("Poll"); driverUser.setLastName("Brien"); driverUser.setType(server); driverUser.setDriver(true); driverUser.setActive(true); dao.saveOrUpdate(driverUser); OrderTypeDAO orderTypeDAO = new OrderTypeDAO(); OrderType orderType = new OrderType(); orderType.setName("DINE IN"); orderType.setShowTableSelection(true); orderType.setCloseOnPaid(true); orderType.setEnabled(true); orderType.setShouldPrintToKitchen(true); orderType.setShowInLoginScreen(true); orderTypeDAO.save(orderType); orderType = new OrderType(); orderType.setName("TAKE OUT"); orderType.setShowTableSelection(false); orderType.setCloseOnPaid(true); orderType.setEnabled(true); orderType.setPrepaid(true); orderType.setShouldPrintToKitchen(true); orderType.setShowInLoginScreen(true); orderTypeDAO.save(orderType); orderType = new OrderType(); orderType.setName("RETAIL"); orderType.setShowTableSelection(false); orderType.setCloseOnPaid(true); orderType.setEnabled(true); orderType.setShouldPrintToKitchen(false); orderType.setShowInLoginScreen(true); orderTypeDAO.save(orderType); orderType = new OrderType(); orderType.setName("HOME DELIVERY"); orderType.setShowTableSelection(false); orderType.setCloseOnPaid(false); orderType.setEnabled(true); orderType.setShouldPrintToKitchen(true); orderType.setShowInLoginScreen(true); orderType.setRequiredCustomerData(true); orderType.setDelivery(true); orderTypeDAO.save(orderType); DiscountDAO discountDao = new DiscountDAO(); Discount discount1 = new Discount(); discount1.setName("Buy 1 and get 1 free"); discount1.setType(1); discount1.setValue(100.0); discount1.setAutoApply(false); discount1.setMinimunBuy(2); discount1.setQualificationType(0); discount1.setApplyToAll(true); discount1.setNeverExpire(true); discount1.setEnabled(true); discountDao.saveOrUpdate(discount1); Discount discount2 = new Discount(); discount2.setName("Buy 2 and get 1 free"); discount2.setType(1); discount2.setValue(100.0); discount2.setAutoApply(true); discount2.setMinimunBuy(3); discount2.setQualificationType(0); discount2.setApplyToAll(true); discount2.setNeverExpire(true); discount2.setEnabled(true); discountDao.saveOrUpdate(discount2); Discount discount3 = new Discount(); discount3.setName("10% Off"); discount3.setType(1); discount3.setValue(10.0); discount3.setAutoApply(false); discount3.setMinimunBuy(1); discount3.setQualificationType(0); discount3.setApplyToAll(true); discount3.setNeverExpire(true); discount3.setEnabled(true); discountDao.saveOrUpdate(discount3); int terminalId = TerminalConfig.getTerminalId(); if (terminalId == -1) { Random random = new Random(); terminalId = random.nextInt(10000) + 1; } Terminal terminal = new Terminal(); terminal.setId(terminalId); terminal.setName(String.valueOf(terminalId)); //$NON-NLS-1$ TerminalDAO.getInstance().saveOrUpdate(terminal); CashDrawer cashDrawer = new CashDrawer(); cashDrawer.setTerminal(terminal); Currency currency = new Currency(); currency.setName("USD"); currency.setSymbol("$"); currency.setExchangeRate(1.0); currency.setMain(true); CurrencyDAO.getInstance().save(currency); currency = new Currency(); currency.setName("EUR"); currency.setSymbol("E"); currency.setExchangeRate(0.8); CurrencyDAO.getInstance().save(currency); currency = new Currency(); currency.setName("BRL"); currency.setSymbol("B"); currency.setExchangeRate(3.47); CurrencyDAO.getInstance().save(currency); currency = new Currency(); currency.setName("ARS"); currency.setSymbol("P"); currency.setExchangeRate(13.89); CurrencyDAO.getInstance().save(currency); currency = new Currency(); currency.setName("PYG"); currency.setSymbol("P"); currency.setExchangeRate(5639.78); CurrencyDAO.getInstance().save(currency); MenuItemSize menuItemSize = new MenuItemSize(); menuItemSize.setName("SMALL"); menuItemSize.setSortOrder(0); MenuItemSizeDAO.getInstance().save(menuItemSize); menuItemSize = new MenuItemSize(); menuItemSize.setName("MEDIUM"); menuItemSize.setSortOrder(1); MenuItemSizeDAO.getInstance().save(menuItemSize); menuItemSize = new MenuItemSize(); menuItemSize.setName("LARGE"); menuItemSize.setSortOrder(2); MenuItemSizeDAO.getInstance().save(menuItemSize); PizzaCrust crust = new PizzaCrust(); crust.setName("PAN"); crust.setSortOrder(0); PizzaCrustDAO.getInstance().save(crust); crust = new PizzaCrust(); crust.setName("HAND TOSSED"); crust.setSortOrder(1); PizzaCrustDAO.getInstance().save(crust); Multiplier multiplier = new Multiplier("Regular"); multiplier.setRate(0.0); multiplier.setSortOrder(0); multiplier.setTicketPrefix(""); multiplier.setDefaultMultiplier(true); multiplier.setMain(true); MultiplierDAO.getInstance().save(multiplier); multiplier = new Multiplier("No"); multiplier.setRate(0.0); multiplier.setSortOrder(1); multiplier.setTicketPrefix("No"); multiplier.setDefaultMultiplier(false); MultiplierDAO.getInstance().save(multiplier); multiplier = new Multiplier("Half"); multiplier.setRate(50.0); multiplier.setSortOrder(2); multiplier.setTicketPrefix("Half"); multiplier.setDefaultMultiplier(false); MultiplierDAO.getInstance().save(multiplier); multiplier = new Multiplier("Quarter"); multiplier.setRate(25.0); multiplier.setSortOrder(3); multiplier.setTicketPrefix("Quarter"); multiplier.setDefaultMultiplier(false); MultiplierDAO.getInstance().save(multiplier); multiplier = new Multiplier("Extra"); multiplier.setRate(200.0); multiplier.setSortOrder(4); multiplier.setTicketPrefix("Extra"); multiplier.setDefaultMultiplier(false); MultiplierDAO.getInstance().save(multiplier); multiplier = new Multiplier("Triple"); multiplier.setRate(300.0); multiplier.setSortOrder(5); multiplier.setTicketPrefix("Triple"); multiplier.setDefaultMultiplier(false); MultiplierDAO.getInstance().save(multiplier); multiplier = new Multiplier("Sub"); multiplier.setRate(100.0); multiplier.setSortOrder(6); multiplier.setTicketPrefix("Sub"); multiplier.setDefaultMultiplier(false); MultiplierDAO.getInstance().save(multiplier); if (!exportSampleData) { return true; } DataImportAction.importMenuItems(DatabaseUtil.class.getResourceAsStream("/floreantpos-menu-items.xml")); return true; } catch (Exception e) { PosLog.error(DatabaseUtil.class, e.getMessage()); logger.error(e); return false; } }
From source file:com.forsrc.utils.ExportDb.java
License:Apache License
/** * Init./*w ww .j ava 2 s . c om*/ */ public static void init() { Configuration cfg = new Configuration().configure(); String isInit = cfg.getProperty("isInitDb"); if (isInit == null || !"true".equals(isInit)) { return; } //4.x //SchemaExport export = new SchemaExport(cfg); //export.create(true, false); //ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() //.applySettings(cfg.getProperties()).buildServiceRegistry(); //SessionFactory sessionFactory = cfg.buildSessionFactory(serviceRegistry); ServiceRegistry serviceRegistry = null; try { //5.x serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); MetadataImplementor metadata = (MetadataImplementor) new MetadataSources(serviceRegistry) .buildMetadata(); SchemaExport export = new SchemaExport(serviceRegistry, metadata); export.create(true, false); StandardServiceRegistryBuilder.destroy(serviceRegistry); } catch (Exception e) { e.printStackTrace(); //LogUtils.LOGGER.error(e.getMessage(), e); } finally { if (serviceRegistry != null) { StandardServiceRegistryBuilder.destroy(serviceRegistry); serviceRegistry = null; } } Session session = null; try { //ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); //SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata() //.buildSessionFactory(); //SessionFactory sessionFactory = HibernateSessionFactory.getSessionFactory(); serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata() .buildSessionFactory(); session = sessionFactory.openSession(); executeNamedQuery(session, "sql_user_insert_admin"); executeNamedQuery(session, "sql_book_category_insert_init"); executeNamedQuery(session, "sql_book_insert_init"); } catch (Exception e) { e.printStackTrace(); //LogUtils.LOGGER.error(e.getMessage(), e); } finally { if (serviceRegistry != null) { StandardServiceRegistryBuilder.destroy(serviceRegistry); serviceRegistry = null; } } }
From source file:com.github.antennaesdk.messageserver.db.H2.H2Database.java
License:Apache License
public void generateSchemaAndCreateTables(SimpleDriverDataSource dataSource) { // Get the tables that are already in the DATABASE List<String> tables = new ArrayList<>(); try {/*from w w w. j ava2 s . co m*/ Connection connection = dataSource.getConnection(); DatabaseMetaData databaseMetadata = connection.getMetaData(); ResultSet resultSet = databaseMetadata.getTables(null, null, null, new String[] { "TABLE" }); while (resultSet.next()) { String table = resultSet.getString(3); logger.info("Table : " + table + " ... exists"); tables.add(table); } } catch (SQLException e) { e.printStackTrace(); } // Get the tables that are needed from Entity Classes List<Class> tablesToCreate = new ArrayList<>(); for (Class<?> c : entityClasses) { // get the table names Table table = c.getAnnotation(Table.class); logger.info("Entity: " + c.getName() + " , Table: " + table.name()); boolean isExisting = false; for (String dbTable : tables) { if (dbTable.equals(table.name())) { isExisting = true; break; } } if (!isExisting) { // these tables must be created tablesToCreate.add(c); } } // Check whether the tables need to be created... if (tablesToCreate.size() == 0) { logger.info("Tables already exist... "); return; } else { logger.info("Creating tables..."); } //create a minimal configuration org.hibernate.cfg.Configuration cfg = new org.hibernate.cfg.Configuration(); cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); cfg.setProperty("hibernate.hbm2ddl.auto", "create"); // create a temporary file to write the DDL File ddlFile = null; try { File dir = getDirectoryFromClasspath(); ddlFile = File.createTempFile("H2_", ".SQL", dir); ddlFile.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); } // add the tables to be created for (Class c : tablesToCreate) { cfg.addAnnotatedClass(c); } //build all the mappings, before calling the AuditConfiguration cfg.buildMappings(); cfg.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, ddlFile.getName()); cfg.getProperties().setProperty("hibernate.connection.driver_class", "org.h2.Driver"); cfg.getProperties().setProperty("hibernate.connection.url", dataSource.getUrl()); cfg.getProperties().setProperty("hibernate.connection.username", dataSource.getUsername()); cfg.getProperties().setProperty("hibernate.connection.password", dataSource.getPassword()); //execute the export SchemaExport export = new SchemaExport(cfg); export.setDelimiter(";"); export.setFormat(true); // create the tables in the DB and show the DDL in console export.create(true, true); }
From source file:com.ikon.dao.HibernateUtil.java
License:Open Source License
/** * Generate database schema and initial data for a defined dialect *//* w w w .j av a 2s . c o m*/ public static void generateDatabase(String dialect) throws IOException { // Configure Hibernate log.info("Exporting Database Schema..."); String dbSchema = EnvironmentDetector.getUserHome() + "/schema.sql"; Configuration cfg = getConfiguration().configure(); cfg.setProperty("hibernate.dialect", dialect); SchemaExport se = new SchemaExport(cfg); se.setOutputFile(dbSchema); se.setDelimiter(";"); se.setFormat(false); se.create(false, false); log.info("Database Schema exported to {}", dbSchema); String initialData = new File("").getAbsolutePath() + "/src/main/resources/default.sql"; log.info("Exporting Initial Data from '{}'...", initialData); String initData = EnvironmentDetector.getUserHome() + "/data.sql"; FileInputStream fis = new FileInputStream(initialData); String ret = DatabaseDialectAdapter.dialectAdapter(fis, dialect); FileWriter fw = new FileWriter(initData); IOUtils.write(ret, fw); fw.flush(); fw.close(); log.info("Initial Data exported to {}", initData); }
From source file:com.ironiacorp.persistence.hibernate.GenericHibernateDataSource.java
License:Open Source License
/** * Create the database.//www . j a v a2 s . co m * * @throws RuntimeException If an error is found when running the DDL script. */ public void createDB() { log.debug("Creating the database"); log.debug(getCreateDDLScript()); SchemaExport ddl = new SchemaExport(hibernateConfig); List exceptions = null; ddl.create(false, true); exceptions = handleExceptions(ddl); if (!exceptions.isEmpty()) { throw new RuntimeException("exception.bootstrap.createdb", (Exception) ddl.getExceptions().get(0)); } }