问题
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:
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.
回答2:
What about?
<mapping assembly="SomeAssemblyName" />
回答3:
I was looking for a similar solution and found the answer from another question here. You should be using spring to make that work.
- Create a class EntityScannerSessionFactoryBean extending AnnotationSessionFactoryBean
- Copy the code from the link(Its a great answer make sure you read it). to your new class.
- Add the below to map that class as sessionFactory in your application context.
bean id="sessionFactory" class="com.foo.EntityScannerSessionFactoryBean">
回答4:
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.
回答5:
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.
来源:https://stackoverflow.com/questions/2419802/hibernate-configuration-session-factory-scanning