'Hibernate mapping classes from hibernate.cfg.xml

For class mapping from hibernate.cfg.xml I use these format below:

<mapping class="packageName.className1"/>
<mapping class="packageName.className2"/>
<mapping class="packageName.className3"/>

How can I map all classes in a package, by using one mapping row? For Example: <mapping class="packageName.*"/> using bla-star doesn't work!



Solution 1:[1]

Error "Error parsing XML: hibernate2.cfg.xml(22) Attribute "value" must be declared for element type "property" - is not related to package mapping.

<mapping class="packageName.*"/> should work.

Issue is with the property element. property element doesnt have any attribute called value.

Try :

<property name="hibernate.archive.autodetection">class, hbm</property>

Instead of :

<property name="hibernate.archive.autodetection" value="class, hbm" />

Solution 2:[2]

As far as I know there is no direct way to scan packages from hibernate.cfg.xml. You can use other frameworks that wraps session factory creation with their own classes.

For example you can use spring-orm to scan packages while creating your session factory instance.

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="your-own-datasource"/>
    <property name="configLocation" value="classpath*:hibernate.cfg.xml"/>
    <property name="packagesToScan" value="your.package.name"/>
</bean>

Or you can write your own SessionFactoryWrapper. While creating SessionFactory you can scan packages and than add them on runtime.

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import javax.persistence.Entity;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class SessionFactoryWrapper {

    private final SessionFactory sessionFactory;

    public SessionFactoryWrapper(final String...packagesToScan) {
        this.sessionFactory = this.createSessionFactory(packagesToScan);
    }

    private SessionFactory createSessionFactory(final String[] packagesToScan) {
        final Configuration configuration = new Configuration();
        configuration.configure(); // Reads hibernate.cfg.xml from classpath

        for (String packageToScan : packagesToScan) {
            this.getEntityClasses(packageToScan).stream().forEach( configuration::addAnnotatedClass);
        }

        final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        return configuration.buildSessionFactory(serviceRegistry);
    }

    private Collection<Class> getEntityClasses(final String pack) {
        final StandardJavaFileManager fileManager = ToolProvider.getSystemJavaCompiler().getStandardFileManager(null, null, null);
        try {
            return StreamSupport.stream(fileManager.list(StandardLocation.CLASS_PATH, pack, Collections.singleton(JavaFileObject.Kind.CLASS), false).spliterator(), false)
                    .map(FileObject::getName)
                    .map(name -> {
                        try {
                            final String[] split = name
                                    .replace(".class", "")
                                    .replace(")", "")
                                    .split(Pattern.quote(File.separator));

                            final String fullClassName = pack + "." + split[split.length - 1];
                            return Class.forName(fullClassName);
                        } catch (ClassNotFoundException e) {
                            throw new RuntimeException(e);
                        }

                    })
                    .filter(aClass -> aClass.isAnnotationPresent(Entity.class))
                    .collect(Collectors.toCollection(ArrayList::new));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rahman
Solution 2