Saturday, February 19, 2011

Configure Hibernate Application to use multiple database

Hi folks,

                In last couple of weeks, My team was working on configuring our application's Hibernate layer to use multiple database schema. Following are the steps we followed:
  1.  created hibernate.properties and hibernate.cfg.xml  for every database schema with different name eg. for schema zMRDB, we have created hibernatezMRDB.properties and hibernatezMRDB.cfg.xml files.
  2. don't use hibernate.properties and hibernate.cfg.xml  default files for any schema
  3. Finally at the time of Session Factory creation use following code
  4. public static SessionFactory getSessionFactory() {
         if (sessionFactory == null) {
       try {
        final Configuration cfg = new Configuration();
        Properties connectionProperties = new Properties();
        InputStream inStream = ThreadLocalUtil.class.getClassLoader().getResourceAsStream("hibernatezMRDB.properties");
        connectionProperties.load(inStream);
        cfg.setProperties(connectionProperties);
        sessionFactory = cfg.configure("hibernatezMRDB.cfg.xml").buildSessionFactory();
        
       
       } catch (Throwable ex) {
        ex.printStackTrace();
       }
      }
      return sessionFactory;
        } 
    
  5. Use SessionFactory returned by method in STEP 3 to open and use session with specific Database.

Tuesday, February 1, 2011

Easy Way to iterate Over Map

public void displayMapContaint(Map<String, String> data) {
  for (Map.Entry<String, String> pair : data.entrySet()) {
   System.out.println("Key: " + pair.getKey() + " Data: "+ pair.getValue());
  }
 }