Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Mapping Package

I'm using Hibernate Annotations.

In all my model classes I annotate like this:

@Entity @Table public class SomeModelClass { // } 

My hibernate.cfg.xml is

<hibernate-configuration>    <session-factory>       <!-- some properties -->        <mapping package="com.fooPackage" />       <mapping class="com.fooPackage.SomeModelClass" />     </session-factory> </hibernate-configuration> 

For every class I add to the com.fooPackage I have to add a line in the hibernate.cfg.xml like this:

<mapping class="com.fooPackage.AnotherModelClass" /> 

Is there a way I can add new model classes but don't need to add this line to hibernate.cfg.xml?

like image 937
Daniel Moura Avatar asked Sep 11 '09 20:09

Daniel Moura


People also ask

What is the mapping in hibernate?

This mapping file instructs Hibernate — how to map the defined class or classes to the database tables? Though many Hibernate users choose to write the XML by hand, but a number of tools exist to generate the mapping document. These include XDoclet, Middlegen and AndroMDA for the advanced Hibernate users.

Does hibernate have mapping?

Define Hibernate Mapping FileThe <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.


1 Answers

Out of the box - no. You can write your own code to detect / register your annotated classes, however. If you're using Spring, you can extend AnnotationSessionFactoryBean and do something like:

@Override protected SessionFactory buildSessionFactory() throws Exception {   ArrayList<Class> classes = new ArrayList<Class>();    // the following will detect all classes that are annotated as @Entity   ClassPathScanningCandidateComponentProvider scanner =     new ClassPathScanningCandidateComponentProvider(false);   scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));    // only register classes within "com.fooPackage" package   for (BeanDefinition bd : scanner.findCandidateComponents("com.fooPackage")) {     String name = bd.getBeanClassName();     try {       classes.add(Class.forName(name));     } catch (Exception E) {       // TODO: handle exception - couldn't load class in question     }   } // for    // register detected classes with AnnotationSessionFactoryBean   setAnnotatedClasses(classes.toArray(new Class[classes.size()]));   return super.buildSessionFactory(); } 

If you're not using Spring (and you should be :-) ) you can write your own code for detecting appropriate classes and register them with your AnnotationConfiguration via addAnnotatedClass() method.

Incidentally, it's not necessary to map packages unless you've actually declared something at package level.

like image 140
ChssPly76 Avatar answered Sep 22 '22 00:09

ChssPly76