Hibernate Mapping Package

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.

Leave a Comment