java 来自 hibernate.cfg.xml 的 Hibernate 映射类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32824823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:50:29  来源:igfitidea点击:

Hibernate mapping classes from hibernate.cfg.xml

javaxmlhibernate

提问by user3174737

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

对于来自 hibernate.cfg.xml 的类映射,我使用以下格式:

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

<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!

如何通过使用一个映射行来映射包中的所有类?例如:<mapping class="packageName.*"/>使用 bla-star 不起作用!

回答by Rehman

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

错误“解析 XML 时出错:hibernate2.cfg.xml(22) 必须为元素类型“属性”声明属性“值” - 与包映射无关。

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

<mapping class="packageName.*"/>应该管用。

Issue is with the propertyelement. propertyelement doesnt have any attribute called value.

问题在于property元素。 property元素没有任何称为value.

Try :

尝试 :

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

Instead of :

代替 :

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

回答by bhdrkn

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.

据我所知,没有直接的方法可以从hibernate.cfg.xml. 您可以使用其他框架,这些框架将会话工厂的创建与它们自己的类包装在一起。

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

例如,您可以spring-orm在创建会话工厂实例时使用扫描包。

<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.

或者您可以编写自己的 SessionFactoryWrapper。在创建 SessionFactory 时,您可以扫描包,然后在运行时添加它们。

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;
    }
}