List of usage examples for org.hibernate.cfg Configuration Configuration
public Configuration()
From source file:com.registrolocacao.conexao.HibernateUtil.java
private static SessionFactory carregarConexao() { try {//from w w w. j a v a 2 s . com Configuration config = new Configuration().configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder registro = new StandardServiceRegistryBuilder(); registro.applySettings(config.getProperties()).build(); StandardServiceRegistry servico = registro.build(); return config.buildSessionFactory(servico); } catch (Throwable e) { throw new ExceptionInInitializerError(e); } }
From source file:com.restfully.shop.test.AnnotationsIllustrationTest.java
License:Open Source License
@Override protected void setUp() throws Exception { // A SessionFactory is set up once for an application sessionFactory = new Configuration().configure() // configures settings from hibernate.cfg.xml .buildSessionFactory();//from w w w . jav a 2 s. c o m }
From source file:com.sakadream.sql.SQLConfigJson.java
License:MIT License
/** * Get Hibernate Configuration Properties using Hibernate API * @param pkgLocation hibernate.cfg.xml's folder location * @return SQLConfig SQLConfig object/*from w w w. j a v a2s.co m*/ */ public static SQLConfig getHibernateCfg(String pkgLocation) { Configuration config = new Configuration(); config.configure(pkgLocation + "hibernate.cfg.xml"); String username = config.getProperty("hibernate.connection.username"); String password = config.getProperty("hibernate.connection.password"); String url = config.getProperty("hibernate.connection.url"); SQLConfig sqlconfig = new SQLConfig(); sqlconfig.setDialect(dl.getDialectByUrl(url)); sqlconfig.setUsername(username); sqlconfig.setPassword(password); sqlconfig.setHibernateConfig(true); return sqlconfig; }
From source file:com.sakadream.sql.SQLConfigJson.java
License:MIT License
/** * Set hibernate.cfg.xml properties from SQLConfig object * @param config SQLConfig object// w ww .j a va 2 s .c o m * @param pkgLocation hibernate.cfg.xml's folder location */ public static void setHibernateCfg(SQLConfig config, String pkgLocation) { String url = ""; if (config.getUrl() == null) { url = config.generateURL(); } else { url = config.getUrl(); } Configuration HBMconfig = new Configuration(); HBMconfig.configure(pkgLocation + "hibernate.cfg.xml"); HBMconfig.setProperty("hibernate.connection.username", config.getUsername()); HBMconfig.setProperty("hibernate.connection.password", config.getPassword()); HBMconfig.setProperty("hibernate.connection.url", url); }
From source file:com.sam.moca.db.hibernate.HibernateTools.java
License:Open Source License
synchronized public static SessionFactory getSessionFactory(final MocaContext ctx) { if (_factory == null) { Configuration cfg = new Configuration(); // First, load up default properties stored in MOCA Properties props = new Properties(); try {//from w ww. j a va 2 s .co m _loadProperties(props, HibernateTools.class.getResourceAsStream("resources/hibernate.properties")); } catch (IOException e) { ctx.logWarning("Unable to load hibernate properties: " + e); _sqlLogger.debug("Unable to load hibernate properties", e); } // Next, default the database dialect, based on MOCA's idea // of the database type. String dbType = ctx.getDb().getDbType(); if (dbType.equals("ORACLE")) { props.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect"); } else if (dbType.equals("MSSQL")) { props.setProperty("hibernate.dialect", "com.sam.moca.db.hibernate.UnicodeSQLServerDialect"); } else if (dbType.equals("H2")) { props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); } SystemContext systemContext = ServerUtils.globalContext(); // We get the data files in reverse. File[] files = systemContext.getDataFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.equals("hibernate.properties")) { return true; } return false; } }, true); // For each directory in the list, look for a // hibernate.properties file. for (File propFile : files) { if (propFile.canRead()) { try { ctx.trace(MocaTrace.SQL, "Loading Properties file: " + propFile); _loadProperties(props, new FileInputStream(propFile)); } catch (IOException e) { ctx.logWarning("Unable to load properties " + propFile + ": " + e); _sqlLogger.debug("Unable to load hibernate properties", e); } catch (HibernateException e) { ctx.logWarning("Unable to load properties " + propFile + ": " + e); _sqlLogger.debug("Unable to load hibernate properties", e); } } } cfg.setProperties(props); // We get the data files in reverse. files = systemContext.getDataFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.equals("hibernate.cfg.xml")) { return true; } return false; } }, true); // Now look for hibernate config files in each mappings directory. for (File xmlFile : files) { if (xmlFile.canRead()) { try { ctx.trace(MocaTrace.SQL, "Loading config file: " + xmlFile); cfg.configure(xmlFile); } catch (HibernateException e) { ctx.logWarning("Unable to load config file " + xmlFile + ": " + e); _sqlLogger.debug("Unable to load hibernate config", e); } } } _factory = cfg.buildSessionFactory(); StatisticsService statsMBean = new StatisticsService(); statsMBean.setSessionFactory(_factory); Exception excp = null; MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); try { mBeanServer.registerMBean(statsMBean, new ObjectName("Hibernate:application=Statistics")); } catch (InstanceAlreadyExistsException e) { excp = e; } catch (MBeanRegistrationException e) { excp = e; } catch (NotCompliantMBeanException e) { excp = e; } catch (MalformedObjectNameException e) { excp = e; } if (excp != null) { _sqlLogger.warn("Failed to export Hibernate Statistics " + "Service. Runtime statistics will not be viewable " + "from MBeans!", excp); } } return _factory; }
From source file:com.sapuraglobal.hrms.ejb.DaoDelegate.java
private DaoDelegate() { cfg = new Configuration(); //populate the hibernate configuration //cfg.configure("hibernate.cfg.xml"); cfg.configure();/* w w w . j av a 2 s . c om*/ ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()); sessionFactory = cfg.buildSessionFactory(ssrb.build()); }
From source file:com.seavus.library.db.HLibDB.java
@Override public void connect() { configuration = new Configuration(); serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); configuration.addAnnotatedClass(Book.class); configuration.addAnnotatedClass(Magazine.class); configuration.addAnnotatedClass(Publication.class); configuration.addAnnotatedClass(Member.class); configuration.addAnnotatedClass(Membership.class); configuration.addAnnotatedClass(Loan.class); sessionFactory = configuration.buildSessionFactory(serviceRegistry); hibernateTemplate = new HibernateTemplate(sessionFactory); }
From source file:com.seer.datacruncher.persistence.manager.DBConnectionChecker.java
License:Open Source License
public DBConnectionChecker(String database_type, String host, int port, String database_name, String username, String password) {// w ww . j a va 2 s. co m //initialize the fields this.database_type = database_type; this.host = host; this.port = port; this.database_name = database_name; this.username = username; this.password = password; if (this.database_type.equals("") || this.host.equals("") || this.port == 0 || this.database_name.equals("") || this.username.equals("")) { checkParams = false; } else { //identify the appropriate driver String db_type = database_type.toUpperCase(); //Added following line of code by KGandhi db_type = db_type.replaceAll(" ", ""); JDBCDriver driver = JDBCDriver.valueOf(db_type); //load the appropriate driver String drivername = driver.getJDBCDriverClass(); // String databaseConnStr = driver.getDatabaseConnStr(); try { Class.forName(drivername); } catch (ClassNotFoundException e) { log.error("Driver error: " + e.getMessage()); } //set the new configuration cfg = new Configuration(); cfg.setProperty("hibernate.connection.driver_class", drivername); cfg.setProperty("hibernate.connection.username", this.username); cfg.setProperty("hibernate.connection.password", this.password); QuickDBManager.Dialect dialect = QuickDBManager.Dialect.valueOf(db_type.toUpperCase()); cfg.setProperty("hibernate.dialect", dialect.getDialectClass()); cfg.setProperty("hibernate.connection.release_mode", "on_close"); String connectionurl = driver.getConnectionUrl() + host + ":" + port + databaseConnStr + this.database_name; cfg.setProperty("hibernate.connection.url", connectionurl); //part reserved to connection pool : in this case we need //just one connection cfg.setProperty("c3p0.min_size", String.valueOf(1)); cfg.setProperty("c3p0.max_size", String.valueOf(1)); cfg.setProperty("c3p0.max_statements", String.valueOf(0)); cfg.setProperty("c3p0.timeout", String.valueOf(timeout)); cfg.setProperty("testConnectionOnCheckin", String.valueOf(true)); } }
From source file:com.seer.datacruncher.spring.ApplicationConfigCreateController.java
License:Open Source License
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Create create = new Create(); ServletOutputStream out = null;//ww w . ja v a2s . co m response.setContentType("application/json"); out = response.getOutputStream(); String configType = request.getParameter("configType"); if (configType.equals("database")) { if (checkDatabaseConnection(request)) { ApplicationConfigEntity appConfigEntity = new ApplicationConfigEntity(); appConfigEntity.setConfigType(ApplicationConfigType.DATABASE); appConfigEntity.setDatabaseName(request.getParameter("databaseName")); appConfigEntity.setHost(request.getParameter("host")); appConfigEntity.setIdDatabaseType(Integer.parseInt(request.getParameter("idDatabaseType"))); appConfigEntity.setPassword(request.getParameter("password")); appConfigEntity.setPort(request.getParameter("port")); appConfigEntity.setUserName(request.getParameter("userName")); try { Configuration conf = new Configuration().configure(); conf.setProperty("hibernate.connection.url", em.getEntityManagerFactory().getProperties().get("hibernate.connection.url") + "?relaxAutoCommit=" + em.getEntityManagerFactory().getProperties() .get("hibernate.connection.autocommit")); new SchemaExport(conf).create(true, true); } catch (Exception ex) { //ex.printStackTrace(); } create = applicationConfigDao.create(appConfigEntity); } else { create.setMessage(I18n.getMessage("error.databaseConnectionError")); create.setSuccess(false); } } else if (configType.equals("userProfile")) { String userName = request.getParameter("userName"); String password = request.getParameter("password"); String name = request.getParameter("name"); String email = request.getParameter("email"); long idAlert = Long .parseLong(request.getParameter("idAlert").isEmpty() ? "0" : request.getParameter("idAlert")); String surname = request.getParameter("surname"); String language = request.getParameter("language"); String dob = request.getParameter("dob"); Date date = null; if (dob != null && dob.trim().length() > 0) { try { date = new SimpleDateFormat("dd/MMM/yyyy").parse(dob); } catch (Exception ex) { ex.printStackTrace(); } } UserEntity userEntity = new UserEntity(userName, password, name, surname, email, 1, 1, language, idAlert, -1, date, "classic"); create = usersDao.create(userEntity); create.setMessage(I18n.getMessage("success.userProfileSaved")); } else if (configType.equals("ftp")) { ApplicationConfigEntity appConfigEntity = new ApplicationConfigEntity(); appConfigEntity.setConfigType(ApplicationConfigType.FTP); appConfigEntity.setUserName(request.getParameter("userName")); appConfigEntity.setPassword(request.getParameter("password")); appConfigEntity.setInputDir(request.getParameter("inputDirectory")); appConfigEntity.setOutputDir(request.getParameter("outputDirectory")); try { appConfigEntity.setServerPort(Integer.parseInt(request.getParameter("serverPort"))); create = applicationConfigDao.create(appConfigEntity); create.setMessage(I18n.getMessage("success.ftpConfigSaved")); } catch (Throwable t) { create = new Create(); create.setSuccess(false); create.setMessage(I18n.getMessage("error.ftpConfigPortInNotANumber")); } } else if (configType.equals("email")) { ApplicationConfigEntity appConfigEntity = new ApplicationConfigEntity(); String serverUrl = getServerURL(request.getRequestURL().toString()); if (!serverUrl.equals("")) { appConfigEntity.setConfigType(ApplicationConfigType.APPLURL); appConfigEntity.setHost(serverUrl); System.out.println(request.getRequestURL().toString()); create = applicationConfigDao.create(appConfigEntity); appConfigEntity = new ApplicationConfigEntity(); } appConfigEntity.setConfigType(ApplicationConfigType.EMAIL); appConfigEntity.setUserName(request.getParameter("userName")); appConfigEntity.setPassword(request.getParameter("password")); appConfigEntity.setHost(request.getParameter("host")); appConfigEntity.setPort(request.getParameter("port")); appConfigEntity.setProtocol(request.getParameter("protocol")); appConfigEntity.setEncoding(request.getParameter("encoding")); appConfigEntity.setSmtpsTimeout(request.getParameter("smtpstimeout")); appConfigEntity.setIsStarTtls(Integer .parseInt(request.getParameter("starttls") == null ? "0" : request.getParameter("starttls"))); appConfigEntity .setIsSmtpsAuthenticate(Integer.parseInt(request.getParameter("smtpsAuthenticate") == null ? "0" : request.getParameter("smtpsAuthenticate"))); create = applicationConfigDao.create(appConfigEntity); create.setMessage(I18n.getMessage("success.emailConfigSaved")); } ObjectMapper mapper = new ObjectMapper(); out.write(mapper.writeValueAsBytes(create)); out.flush(); out.close(); return null; }
From source file:com.sell.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); int moneyStock = 0; int money = 0; try {//ww w . j a va2 s . c o m HttpSession session = request.getSession(true); Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file SessionFactory factory = cfg.buildSessionFactory(); Session session1 = factory.openSession(); int p = (Integer) session.getAttribute("price"); String UEmail = (String) session.getAttribute("email"); Date d = new Date(); int idx = Integer.parseInt(request.getParameter("i")); String comp = request.getParameter("comp"); String Owner_email = request.getParameter("email"); System.out.println("id" + idx); System.out.println("c" + comp); System.out.println("email" + Owner_email); Transaction t3 = session1.beginTransaction(); List list = session1.createQuery("from com.ShareCom Where COMP ='" + comp + "'").list(); Iterator iterator = list.iterator(); for (int j = 0; j < list.size(); j++) { ShareCom user = (ShareCom) iterator.next(); moneyStock = user.getShare_rate(); } PrintWriter out = response.getWriter(); t3.commit(); Transaction t4 = session1.beginTransaction(); List list1 = session1.createQuery("from com.StockUser Where EMAIL='" + Owner_email + "'").list(); Iterator iterator1 = list1.iterator(); for (int j = 0; j < list.size(); j++) { StockUser user = (StockUser) iterator1.next(); money = user.getMoney(); } t4.commit(); ; money = money - moneyStock; Transaction t2 = session1.beginTransaction(); session1.createSQLQuery( "UPDATE STOCK.STOCKUSER set MONEY=" + money + " WHERE EMAIL='" + Owner_email + "' ") .executeUpdate(); t2.commit(); p = p + moneyStock; session.removeAttribute("price"); session.setAttribute("price", p); Transaction t5 = session1.beginTransaction(); session1.createSQLQuery("UPDATE STOCK.STOCKUSER set MONEY=" + p + " WHERE EMAIL='" + UEmail + "' ") .executeUpdate(); t5.commit(); Transaction t1 = session1.beginTransaction(); session1.createSQLQuery("UPDATE STOCK.ShareBuy set END_RATE=" + moneyStock + " WHERE USEREMAIL='" + UEmail + "' AND ID=" + idx + " ").executeUpdate(); t1.commit(); Transaction t6 = session1.beginTransaction(); session1.createSQLQuery("UPDATE STOCK.ShareBuy set STATUS='SOLD' WHERE USEREMAIL='" + UEmail + "' AND ID=" + idx + " ").executeUpdate(); t6.commit(); Transaction to = session1.beginTransaction(); TransactionT tra = new TransactionT(); tra.setAmount(moneyStock); tra.setSellermail(UEmail); tra.setStatus("S-U"); tra.setD(d); tra.setUsermail(Owner_email); session1.persist(tra); to.commit(); System.out.println(idx); out.print("Success"); } catch (Exception ee) { ee.printStackTrace(); } }