ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Hibernate for Java SE
Pages: 1, 2, 3


Properties props = new Properties();
try {
    props.load(props.getClass()
    .getResourceAsStream("hibernate.properties"));
}catch(Exception e){
    System.out.println("Error loading hibernate "+
     "properties.");
    e.printStackTrace();
    System.exit(0);
}

String driver = 
    props.getProperty("hibernate.connection." +
     "driver_class");
String connUrl =
    props.getProperty("hibernate.connection.url");
String username =
    props.getProperty("hibernate.connection." +
     "username");
String password =
    props.getProperty("hibernate.connection.password");
            
// In my examples, I use Postgres, but Hibernate 
// supports virtually every popular dbms out there.
Class.forName("org.postgresql.Driver");
Connection conn =
    DriverManager.getConnection(connUrl, username, 
     password);

Configuration cfg = new Configuration(); 
cfg.setProperties( props );
SessionFactory sessions = cfg.buildSessionFactory();
Session session = sessions.openSession(conn);

This will give you a Hibernate Session object that is ready to use. However, we still need to figure out how to use the existing entity mappings. The book Hibernate in Action, section 2.3.1, shows how you can load in entity XML mapping files, like so:



Configuration cfg = new Configuration(); 
cfg.addResource("hello/Message.hbm.xml"); 
cfg.setProperties( System.getProperties() ); 
SessionFactory sessions = cfg.buildSessionFactory();

This code clearly shows the loading of the Message entity definition from the hello package. This is fine for a few examples, but extremely tedious and error-prone for more than just a few entities. Plus, not only are the mappings hard-coded, they're maintained manually and you now have to update the loader code every time a new entity is added! Yuck. There is an easier way to discover and load these mappings so that they will always be as current as the latest .jar is.

First off, as in your web or enterprise app, your mapping files will need to be in the classpath in order for Hibernate to work correctly. This is a good thing, since all you will have to do is use that same .jar and find those mapping file names. Since you also may have multiple .jar files in your classpath, you'll need to specify which one contains your mappings. The following is one way to find those mappings.

String cp = System.getProperty("java.class.path");
String jarFile = null;
List   hbmList = null;

String[] cparr = cp.split("\\:");
for(int j=0;j<cparr.length;j++){
    // The following assumes our entities 
    // are wrapped up in a jar file 
    // called 'dbobjs.jar'
    if(cparr[j].indexOf("dbobjs.jar") != -1)
      jarFile=(cparr[j]);
}

if(jarFile != null){
    JarFile jar = new JarFile(new File(jarFile));
    Enumeration e = jar.entries();
    if(e.hasMoreElements()){
        hbmList = new ArrayList();
            while(e.hasMoreElements()){
                // Object comes back
                // as JarFile$JarFileEntry
                JarEntry entry = 
                  (JarEntry)e.nextElement();
                if(entry.getName()
                   .indexOf(".hbm.xml") != -1){ 
                    hbmList.add(entry.getName());
                }
            }
    }else {
        System.out.println("Error: The entity "+
        "jar dbobjs.jar was not found in " +
        "classpath: " + cp);
    }
}

The above code essentially grabs the classpath system property that the VM was initialized with, looks for the .jar file that contains the entity mapping files, parses the names of those files, and then adds them to an ArrayList. When we have the ArrayList with the full names of each of the entity mappings, they can then be passed to the Hibernate Configuration object like so:

Configuration cfg = new Configuration(); 

Iterator iterator = hbmFileNames.iterator();
while(iterator.hasNext()){
    cfg.addResource((String)iterator.next()); 
}

Once we have our Hibernate Session object all set up with the proper mappings, we're ready to go to the next step: putting the entities to use.

Pages: 1, 2, 3

Next Pagearrow