Hibernate - Create hibernate.cfg.xml
this is how to generate a cfg.xml file containing only your mapped classes
Whats about
we all know Hibernate is a cool thing and we all know it is hell of easy to generate your Mapping files with XDoclet and Ant
<taskdef name="hibernatedoclet" classname="xdoclet.modules.hibernate.HibernateDocletTask" classpathref="lib" />
<hibernatedoclet verbose="true" destdir="${src_generate.directory}" mergedir="${merge.dir}">
<fileset dir="${src_core.directory}">
<include name="**/hibernate/**/*.java" />
</fileset>
<hibernate version="3.0" />
</hibernatedoclet>
thats all what you need for generated Mapping files.
Problem
My problem was just that I also want to have the hibernate.cfg.xml to be generated. So the old XDoclet version can't do this and the new XDoclet version needs so many parameters like dialect.
I don't want to provide a dialect, all I wanna provide is a jar file with my mapped classes as Library and a default cfg. File. The Reason for this is that I'm building a small library as flexible as possible and want to support more then one dialect. I also wanna give the user the possibility to define his own properties.
So I googled a litte bit and found an approach with beanshell. Do I really want to mix beanshell, hibernate, ant, xdoclet and java?
I don't think so!
Solution
Let's write an ant task to generate a minimal hibernate.cfg.xml File for my library. We also need a little Helper Class to actually configure our session too use the specific file, by default.
Finally the resulting ant fragment
and the generated file
Source Hibernate Util
This little util is based on the Hibernate Documentation Example. So thanx again Opensource.
package edu.ucdavis.genomics.metabolomics.binbase.bdi.connection;
import java.net.URL;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilderFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.w3c.dom.Document;
import edu.ucdavis.genomics.metabolomics.util.config.XMLConfigurator;
import edu.ucdavis.genomics.metabolomics.util.database.DriverUtilities;
/**
* util to help us with hibernate
* @author wohlgemuth
*
*/
public class HibernateUtil {
public static final SessionFactory sessionFactory;
static {
try {
XMLConfigurator configurator = new XMLConfigurator();
Properties p = DriverUtilities.createConnectionProperties(configurator.getProperties());
Configuration c = new Configuration();
//configure from url
URL url = HibernateUtil.class.getResource("/config/hibernate.cfg.xml");
if(url == null){
throw new Exception("you must have the file /config/hibernate.cfg.xml in your classpath");
}
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openStream());
c.setProperties(p);
c.configure(d);
sessionFactory = c.buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this thread has none yet
if (s == null) {
s = sessionFactory.openSession();
// Store it in the ThreadLocal variable
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}
Source Ant Task
package edu.ucdavis.genomics.metabolomics.ant.task.hibernate;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
/**
* @author wohlgemuth
* generates the minimal hibernate configfile
*/
public class GenerateConfig extends Task{
String generateDir;
String outputDir;
public void execute() throws BuildException {
super.execute();
if(generateDir == null){
throw new BuildException("you must set a directory");
}
if(outputDir == null){
throw new BuildException("you must set a directory");
}
File dir = new File(generateDir);
File file = new File(outputDir+"/hibernate.cfg.xml");
if(dir.exists() == false){
throw new BuildException("directory " + dir + " doesn't exist");
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("<!DOCTYPE hibernate-configuration PUBLIC \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\" \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\n");
writer.write("<hibernate-configuration>\n");
writer.write("<session-factory>\n");
scan(dir,writer);
writer.write("</session-factory>");
writer.write("</hibernate-configuration>");
writer.flush();
writer.close();
} catch (IOException e) {
throw new BuildException(e);
}
}
private void scan(File dir, BufferedWriter writer) throws IOException{
if(dir.isDirectory()){
File files[] = dir.listFiles();
for(int i = 0; i < files.length; i++){
scan(files[i],writer);
}
}
else{
if(dir.getName().endsWith("hbm.xml")){
String name =dir.toString().substring(this.getGenerateDir().length()+1,dir.toString().length()) ;
name = name.replace('\\','/');
writer.write("<mapping resource=\"" + name+ "\"/>\n");
}
}
}
/**
*
*/
public GenerateConfig() {
super();
}
public String getOutputDir() {
return this.outputDir;
}
public void setOutputDir(String outputDir) {
this.outputDir = outputDir;
}
public String getGenerateDir() {
return this.generateDir;
}
public void setGenerateDir(String generateDir) {
this.generateDir = generateDir;
}
}
we all know Hibernate is a cool thing and we all know it is hell of easy to generate your Mapping files with XDoclet and Ant
<taskdef name="hibernatedoclet" classname="xdoclet.modules.hibernate.HibernateDocletTask" classpathref="lib" />
<hibernatedoclet verbose="true" destdir="${src_generate.directory}" mergedir="${merge.dir}">
<fileset dir="${src_core.directory}">
<include name="**/hibernate/**/*.java" />
</fileset>
<hibernate version="3.0" />
</hibernatedoclet>
thats all what you need for generated Mapping files.
Problem
My problem was just that I also want to have the hibernate.cfg.xml to be generated. So the old XDoclet version can't do this and the new XDoclet version needs so many parameters like dialect.
I don't want to provide a dialect, all I wanna provide is a jar file with my mapped classes as Library and a default cfg. File. The Reason for this is that I'm building a small library as flexible as possible and want to support more then one dialect. I also wanna give the user the possibility to define his own properties.
So I googled a litte bit and found an approach with beanshell. Do I really want to mix beanshell, hibernate, ant, xdoclet and java?
I don't think so!
Solution
Let's write an ant task to generate a minimal hibernate.cfg.xml File for my library. We also need a little Helper Class to actually configure our session too use the specific file, by default.
Finally the resulting ant fragment
<taskdef name="cfg" classname="edu.ucdavis.genomics.metabolomics.ant.task.hibernate.GenerateConfig" classpathref="lib" />
<cfg outputdir="${classes.directory}" generatedir="${classes.directory}/config" />
<cfg outputdir="${classes.directory}" generatedir="${classes.directory}/config" />
and the generated file
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping resource="edu/ucdavis/genomics/metabolomics/ant/task/hibernate/test/a/b.hbm.xml"/>
<mapping resource="edu/ucdavis/genomics/metabolomics/ant/task/hibernate/test/b/b.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<hibernate-configuration>
<session-factory>
<mapping resource="edu/ucdavis/genomics/metabolomics/ant/task/hibernate/test/a/b.hbm.xml"/>
<mapping resource="edu/ucdavis/genomics/metabolomics/ant/task/hibernate/test/b/b.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Source Hibernate Util
This little util is based on the Hibernate Documentation Example. So thanx again Opensource.
package edu.ucdavis.genomics.metabolomics.binbase.bdi.connection;
import java.net.URL;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilderFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.w3c.dom.Document;
import edu.ucdavis.genomics.metabolomics.util.config.XMLConfigurator;
import edu.ucdavis.genomics.metabolomics.util.database.DriverUtilities;
/**
* util to help us with hibernate
* @author wohlgemuth
*
*/
public class HibernateUtil {
public static final SessionFactory sessionFactory;
static {
try {
XMLConfigurator configurator = new XMLConfigurator();
Properties p = DriverUtilities.createConnectionProperties(configurator.getProperties());
Configuration c = new Configuration();
//configure from url
URL url = HibernateUtil.class.getResource("/config/hibernate.cfg.xml");
if(url == null){
throw new Exception("you must have the file /config/hibernate.cfg.xml in your classpath");
}
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openStream());
c.setProperties(p);
c.configure(d);
sessionFactory = c.buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this thread has none yet
if (s == null) {
s = sessionFactory.openSession();
// Store it in the ThreadLocal variable
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}
Source Ant Task
package edu.ucdavis.genomics.metabolomics.ant.task.hibernate;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
/**
* @author wohlgemuth
* generates the minimal hibernate configfile
*/
public class GenerateConfig extends Task{
String generateDir;
String outputDir;
public void execute() throws BuildException {
super.execute();
if(generateDir == null){
throw new BuildException("you must set a directory");
}
if(outputDir == null){
throw new BuildException("you must set a directory");
}
File dir = new File(generateDir);
File file = new File(outputDir+"/hibernate.cfg.xml");
if(dir.exists() == false){
throw new BuildException("directory " + dir + " doesn't exist");
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("<!DOCTYPE hibernate-configuration PUBLIC \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\" \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\n");
writer.write("<hibernate-configuration>\n");
writer.write("<session-factory>\n");
scan(dir,writer);
writer.write("</session-factory>");
writer.write("</hibernate-configuration>");
writer.flush();
writer.close();
} catch (IOException e) {
throw new BuildException(e);
}
}
private void scan(File dir, BufferedWriter writer) throws IOException{
if(dir.isDirectory()){
File files[] = dir.listFiles();
for(int i = 0; i < files.length; i++){
scan(files[i],writer);
}
}
else{
if(dir.getName().endsWith("hbm.xml")){
String name =dir.toString().substring(this.getGenerateDir().length()+1,dir.toString().length()) ;
name = name.replace('\\','/');
writer.write("<mapping resource=\"" + name+ "\"/>\n");
}
}
}
/**
*
*/
public GenerateConfig() {
super();
}
public String getOutputDir() {
return this.outputDir;
}
public void setOutputDir(String outputDir) {
this.outputDir = outputDir;
}
public String getGenerateDir() {
return this.generateDir;
}
public void setGenerateDir(String generateDir) {
this.generateDir = generateDir;
}
}
Created by
zwluxx
Last modified 2005-10-12 08:51 AM
Last modified 2005-10-12 08:51 AM