public static String getColumnName(Class classObj, String attributeName) {
    // Logger.out.debug("classObj, String attributeName "+classObj+" "+attributeName);
    Iterator it = cfg.getClassMapping(classObj).getPropertyClosureIterator();
    while (it.hasNext()) {
      Property property = (Property) it.next();

      // Logger.out.debug("property.getName() "+property.getName());
      // System.out.println();
      // System.out.print("property.getName() "+property.getName()+" ");
      if (property != null && property.getName().equals(attributeName)) {
        // System.out.println("property.getColumnSpan() "+property.getColumnSpan());
        Iterator colIt = property.getColumnIterator();
        while (colIt.hasNext()) {
          Column col = (Column) colIt.next();
          // System.out.println("col "+col.getName());
          return col.getName();
        }
      }
    }

    Property property = cfg.getClassMapping(classObj).getIdentifierProperty();
    // Logger.out.debug("property.getName() "+property.getName());
    if (property.getName().equals(attributeName)) {
      Iterator colIt = property.getColumnIterator(); // y("id").getColumnIterator();
      while (colIt.hasNext()) {
        Column col = (Column) colIt.next();
        return col.getName();
        // System.out.println(col.getName());
      }
    }

    return "";
  }
  /**
   * This method returns the supermost class of the class passed that is in the same package as
   * class
   *
   * @author aarti_sharma
   * @param objClass
   * @return
   */
  public static Class getSupermostClassInPackage(Object obj) {
    Class objClass = obj.getClass();
    Package objPackage = objClass.getPackage();
    Logger.out.debug("Input Class: " + objClass.getName() + " Package:" + objPackage.getName());

    PersistentClass persistentClass = cfg.getClassMapping(objClass);
    if (persistentClass != null && persistentClass.getSuperclass() != null) {

      Logger.out.debug(
          objPackage.getName()
              + " "
              + persistentClass.getName()
              + "*********"
              + persistentClass.getSuperclass().getMappedClass().getPackage().getName());
      Logger.out.debug(
          "!!!!!!!!!!! "
              + persistentClass
                  .getSuperclass()
                  .getMappedClass()
                  .getPackage()
                  .getName()
                  .equals(objPackage.getName()));
      do {
        persistentClass = persistentClass.getSuperclass();
      } while (persistentClass != null);
      Logger.out.debug(
          "Supermost class in the same package:" + persistentClass.getMappedClass().getName());
    } else {
      return objClass;
    }
    return persistentClass.getMappedClass();
  }
 /**
  * This function returns the role Id from hibernate mapping and returns the value
  *
  * @param attributeName
  * @return roleKeyId
  */
 public static String getRoleKeyId(String attributeName) {
   net.sf.hibernate.mapping.Collection col1 = cfg.getCollectionMapping(attributeName);
   Iterator colIt = col1.getElement().getColumnIterator();
   while (colIt.hasNext()) {
     Column col = (Column) colIt.next();
     return (col.getName());
   }
   return "";
 }
Example #4
0
  /**
   * Execute the schema updates
   *
   * @param script print all DDL to the console
   */
  public void execute(boolean script, boolean doUpdate) {

    log.info("Running hbm2ddl schema update");

    Connection connection = null;
    DatabaseMetadata meta;
    Statement stmt = null;
    try {

      try {
        log.info("fetching database metadata");
        connection = connectionProvider.getConnection();
        if (!connection.getAutoCommit()) {
          connection.commit();
          connection.setAutoCommit(true);
        }
        meta = new DatabaseMetadata(connection, dialect);
        stmt = connection.createStatement();
      } catch (SQLException sqle) {
        log.error("could not get database metadata", sqle);
        throw sqle;
      }

      log.info("updating schema");

      String[] createSQL = configuration.generateSchemaUpdateScript(dialect, meta);
      for (int j = 0; j < createSQL.length; j++) {

        final String sql = createSQL[j];
        try {
          if (script) System.out.println(sql);
          if (doUpdate) {
            log.debug(sql);
            stmt.executeUpdate(sql);
          }
        } catch (SQLException e) {
          log.error("Unsuccessful: " + sql);
          log.error(e.getMessage());
        }
      }

      log.info("schema update complete");

    } catch (Exception e) {
      log.error("could not complete schema update", e);
    } finally {

      try {
        if (stmt != null) stmt.close();
        if (connection != null) connection.close();
        if (connectionProvider != null) connectionProvider.close();
      } catch (Exception e) {
        log.error("Error closing connection", e);
      }
    }
  }
 public static String getDataBaseName() {
   String dbName = "";
   String dialect = cfg.getProperty("hibernate.dialect");
   if (dialect.toLowerCase().indexOf("oracle") != -1) {
     dbName = Constants.ORACLE_DATABASE;
   } else if (dialect.toLowerCase().indexOf("mysql") != -1) {
     dbName = Constants.MYSQL_DATABASE;
   } else if (dialect.toLowerCase().indexOf("postgresql") != -1) {
     dbName = Constants.POSTGRESQL_DATABASE;
   }
   return dbName;
 }
  public static String getClassName(String tableName) {
    Iterator it = cfg.getClassMappings();
    PersistentClass persistentClass;
    while (it.hasNext()) {
      persistentClass = (PersistentClass) it.next();
      if (tableName.equalsIgnoreCase(persistentClass.getTable().getName())) {
        return persistentClass.getName();
      }
    }

    return "";
  }
Example #7
0
  public static void main(String[] args) {
    try {
      Configuration cfg = new Configuration();

      boolean script = true;
      // If true then execute db updates, otherwise just generate and display updates
      boolean doUpdate = true;
      String propFile = null;

      for (int i = 0; i < args.length; i++) {
        if (args[i].startsWith("--")) {
          if (args[i].equals("--quiet")) {
            script = false;
          } else if (args[i].startsWith("--properties=")) {
            propFile = args[i].substring(13);
          } else if (args[i].startsWith("--config=")) {
            cfg.configure(args[i].substring(9));
          } else if (args[i].startsWith("--text")) {
            doUpdate = false;
          } else if (args[i].startsWith("--naming=")) {
            cfg.setNamingStrategy(
                (NamingStrategy) ReflectHelper.classForName(args[i].substring(9)).newInstance());
          }
        } else {
          cfg.addFile(args[i]);
        }
      }
      if (propFile != null) {
        Properties props = new Properties();
        props.load(new FileInputStream(propFile));
        new SchemaUpdate(cfg, props).execute(script, doUpdate);
      } else {
        new SchemaUpdate(cfg).execute(script, doUpdate);
      }
    } catch (Exception e) {
      log.error("Error running schema update", e);
      e.printStackTrace();
    }
  }
  /**
   * This method returns the list of subclasses of the className
   *
   * @author aarti_sharma
   * @param className
   * @return
   * @throws ClassNotFoundException
   */
  public static List getSubClassList(String className) throws ClassNotFoundException {
    List list = new ArrayList();
    Class classObj = Class.forName(className);
    Iterator it = cfg.getClassMapping(classObj).getDirectSubclasses();
    while (it.hasNext()) {
      Subclass subClass = (Subclass) it.next();

      System.out.println(subClass.getClass().getName());
      System.out.println("Name " + subClass.getName());
      list.add(subClass.getName());
    }
    return list;
  }
Example #9
0
    static
    {
        try
        {

            InputStream stream = Thread.currentThread().getContextClassLoader().getResource("hibernate.properties").openStream();// Example.class.getResourceAsStream("hibernate.properties");
            try
            {
                pops.load(stream);
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
            Configuration cfg = new Configuration();
            cfg.addClass(Person.class);
            cfg.setProperties(pops);
            _sessions = cfg.buildSessionFactory();
            if (_sessions == null)
            {
                System.out.println("This _session is nULLL");
            }
        }
        catch (MappingException e)
        {
            e.printStackTrace();
        }
        catch (HibernateException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
  /**
   * @param classObj Name of the class.
   * @param attributeName Name of the attribute.
   * @return The width of the column. Returns width of the column or zero.
   */
  public static int getColumnWidth(Class classObj, String attributeName) {
    Iterator it = cfg.getClassMapping(classObj).getPropertyClosureIterator();
    while (it.hasNext()) {
      Property property = (Property) it.next();

      if (property != null && property.getName().equals(attributeName)) {
        Iterator colIt = property.getColumnIterator();
        while (colIt.hasNext()) {
          Column col = (Column) colIt.next();
          return col.getLength();
        }
      }
    }
    // if attribute is not found than the default width will be 50.
    return 50;
  } // getColumnWidth
  /**
   * This Function finds all the relations in i.e Many-To-Many and One-To-Many All the relations are
   * kept in HashMap where key is formed as table1@table2@table_name@attributeName and value is
   * Many-To-Many or One-To-Many
   *
   * @return Map
   */
  private static void findRelations() {
    try {
      Iterator itr1 = cfg.getCollectionMappings();

      while (itr1.hasNext()) {
        Collection col = (Collection) itr1.next();

        if (col.getElement().getClass().getName().equals("net.sf.hibernate.mapping.ManyToOne")) {
          saveRelations(col, "ManyToMany");
        } else {
          saveRelations(col, "OneToMany");
        }
      }
    } catch (Exception e) {
      Logger.out.info("Error occured in fildAllRelations Function:" + e);
    }
  }
  public static void getDATA(Class classObj) {
    net.sf.hibernate.mapping.Collection coll =
        cfg.getCollectionMapping(
            "edu.wustl.catissuecore.domain.CollectionProtocolEvent.specimenRequirementCollection");
    // System.out.println(map);

    System.out.println(coll.getCollectionTable().getName());
    System.out.println(coll.getTable().getName());
    // System.out.println();

    Iterator it = coll.getColumnIterator();

    while (it.hasNext()) {
      // net.sf.hibernate.mapping.Set set = (net.sf.hibernate.mapping.Set)it.next();
      System.out.println(it.next());
    }
  }
Example #13
0
 public SchemaUpdate(Configuration cfg) throws HibernateException {
   this(cfg, cfg.getProperties());
 }
 private void initHibernate() throws MappingException, HibernateException {
   Configuration cfg = new Configuration();
   cfg.addJar("retsdb2-hbm-xml.jar");
   mSessions = cfg.buildSessionFactory();
 }
 /**
  * This method returns the super class of the obj passed
  *
  * @author aarti_sharma
  * @param objClass
  * @return
  */
 public static Class getSuperClass(Object obj) {
   Class objClass = obj.getClass();
   PersistentClass persistentClass = cfg.getClassMapping(objClass);
   PersistentClass superClass = persistentClass.getSuperclass();
   return superClass.getClass();
 }
 public static String getRootTableName(Class classObj) {
   Table tbl = cfg.getClassMapping(classObj).getRootTable();
   if (tbl != null) return tbl.getName();
   return "";
 }