views:

179

answers:

4

We have this hibernate.cfg.xml file. Is there a way to tell Hibernate to just scan a directory instead of having to add an entry here for each class?

<hibernate-configuration>
   <session-factory>
      <mapping class="com.abc.domain.model.A" />
      <mapping class="com.abc.domain.model.B" />
      <mapping class="com.abc.domain.model.C" />
      <mapping class="com.abc.domain.model.D" />
      <mapping class="com.abc.domain.model.E" />
   </session-factory>
</hibernate-configuration>
+1  A: 

What about?

<mapping assembly="SomeAssemblyName" />
Robert
A: 

A NHibernate best practice is to add only an assembly to the configuration before building your ISessionFactory API.

Robert did point it out with the element.

Another way would be to perform runtime configuration as follows:

Configuration cfg = new Configuration();
cfg.AddAssembly(typeof(OneOfYourDomainType).Assembly.Name); // Or something like that by memory.
cfg.Configure();
static ISessionFactory sessionFactory = cfg.BuildSessionFactory();

Making the ISessionFactory static is important as it is very expensive to instantiate.

typeof(OneOfYourDomainType).Assembly.Name returns the name of your assembly containing all of your domain objects, with the proper mappings. Then, adding this, you add the assembly, and you do not need to repeat the process again and again for your domain types.

Will Marcouiller
+3  A: 

To get the discovery mechanism, you need to use Hibernate EntityManager which implements the Java Persistence standard discovery mechanism. Otherwise you need to list your classes.

Pascal Thivent
A: 

Tapestry does this with a utility class that examines the classpath to find the package(s) that contain all of the Hibernate annotated classes and then examines the files on disk to get the class names. If you're ok with having them all live in a single package (or willing to write a more complex classpath utility), you can find them all and then call configuration.addAnnotatedClass(cls). There are caveats, for example, you can't get too fancy with external jars, classes loaded with custom loaders, etc, but for the standard case, it works fine.

You can look at how Tapestry does it here: http://www.java2s.com/Open-Source/Java-Document/Library/Tapestry/org/apache/tapestry/internal/services/ClassNameLocatorImpl.java.htm although that may pull in other Tapestry-specific classes.

Brian Deterling