Java hibernate.cfg.xml 在项目中的位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18736594/
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-08-12 10:36:07  来源:igfitidea点击:

Location of hibernate.cfg.xml in project?

javahibernateorm

提问by gstackoverflow

I created a project with following structure:

我创建了一个具有以下结构的项目:

enter image description here

在此处输入图片说明

HibernateUtil:

休眠实用程序:

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration  configuration = new Configuration().configure( "C:\Users\Nikolay_Tkachev\workspace\hiberTest\src\logic\hibernate.cfg.xml");
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

}

at line

在线

Configuration  configuration = new Configuration().configure( "C:\Users\Nikolay_Tkachev\workspace\hiberTest\src\logic\hibernate.cfg.xml");

I have error

我有错误

Initial SessionFactory creation failed.org.hibernate.HibernateException: C:\Users\Nikolay_Tkachev\workspace\hiberTest\src\logic\hibernate.cfg.xml not found Exception in thread "main" java.lang.ExceptionInInitializerError at logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:19) at logic.HibernateUtil.(HibernateUtil.java:9) at logic.Main.main(Main.java:12) Caused by: org.hibernate.HibernateException: C:\Users\Nikolay_Tkachev\workspace\hiberTest\src\logic\hibernate.cfg.xml not found at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173) at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1947) at org.hibernate.cfg.Configuration.configure(Configuration.java:1928) at logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:14) ... 2 more

初始 SessionFactory 创建失败。 (HibernateUtil.java:19) at logic.HibernateUtil.(HibernateUtil.java:9) at logic.Main.main(Main.java:12) 由:org.hibernate.HibernateException: C:\Users\Nikolay_Tkachev\workspace\在 org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173) at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1947) 处找不到 hiberTest\src\logic\hibernate.cfg.xml org.hibernate.cfg.Configuration.configure(Configuration.java:1928) 在 logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:14) ... 2 更多

What is the reason for the error and how do I fix it?

错误的原因是什么,我该如何解决?

采纳答案by Suresh Atta

Give the path relative to your project.

给出相对于你的项目的路径。

Create a folder called resourcesin your srcand put your config file there.

创建一个名为resources您 的文件夹src并将您的配置文件放在那里。

   configuration.configure("/resources/hibernate.cfg.xml");

And If you check your code

如果你检查你的代码

Configuration  configuration = new Configuration().configure( "C:\Users\Nikolay_Tkachev\workspace\hiberTest\src\logic\hibernate.cfg.xml");
return new Configuration().configure().buildSessionFactory();

In two lines you are creating two configuration objects.

在两行中,您将创建两个配置对象。

That should work(haven't tested) if you write,

如果你写,那应该工作(没有测试过),

Configuration  configuration = new Configuration().configure( "C:\Users\Nikolay_Tkachev\workspace\hiberTest\src\logic\hibernate.cfg.xml");
return  configuration.buildSessionFactory();

But It fails after you deploy on the server,Since you are using system path than project relative path.

但是在服务器上部署后它会失败,因为您使用的是系统路径而不是项目相对路径。

回答by Ha Nguyen

You can put the file "hibernate.cfg.xml" to the src folder (src\hibernate.cfg.xml) and then init the config as the code below:

您可以将文件“hibernate.cfg.xml”放入 src 文件夹(src\hibernate.cfg.xml),然后按照以下代码初始化配置:

Configuration configuration = new Configuration();          
sessionFactory =configuration.configure().buildSessionFactory();

回答by harsh agarwal

try below code it will solve your problem.

试试下面的代码它会解决你的问题。

Configuration  configuration = new Configuration().configure("/logic/hibernate.cfg.xml");

回答by Kisanagaram

Somehow placing under "src" folder didn't work for me.

不知何故放置在“src”文件夹下对我不起作用。

Instead placing cfg.xml as below:

而是将 cfg.xml 放置如下:

[Project Folder]\src\main\resources\hibernate.cfg.xml

worked. Using this code

工作。使用此代码

new Configuration().configure().buildSessionFactory().openSession();

in a file under

在一个文件下

    [Project Folder]/src/main/java/com/abc/xyz/filename.java

In addition have this piece of code in hibernate.cfg.xml

另外在 hibernate.cfg.xml 中有这段代码

<mapping resource="hibernate/Address.hbm.xml" />
<mapping resource="hibernate/Person.hbm.xml" />

Placed the above hbm.xml files under:

将上面的 hbm.xml 文件放在:

EDIT:

编辑:

[Project Folder]/src/main/resources/hibernate/Address.hbm.xml
[Project Folder]/src/main/resources/hibernate/Person.hbm.xml

Above structure worked.

以上结构有效。

回答by Erran Morad

Another reason why this exception occurs is if you call the configure method twice on a Configurationor AnnotatedConfigurationobject like this -

为什么这个异常发生的另一个原因是,如果你调用配置方法两次上一个ConfigurationAnnotatedConfiguration对象这样的-

AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(MyClass.class);
//Use this if config files are in src folder
config.configure();
//Use this if config files are in a subfolder of src, such as "resources"
config.configure("/resources/hibernate.cfg.xml");

Btw, this project structure is inside eclipse.

顺便说一句,这个项目结构在 eclipse 里面。

回答by Do Nhu Vy

This is an reality example when customize folder structure: Folder structure, and initialize class HibernateUtil

enter image description here

这是自定义文件夹结构时的实际示例:文件夹结构,并初始化类 HibernateUtil

在此处输入图片说明

with:

和:

return new Configuration().configure("/config/hibernate.cfg.xml").buildSessionFactory();

mapping: enter image description here

映射: 在此处输入图片说明


with customize entities mapping files:


使用自定义实体映射文件:

        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping class="com.vy.entities.Users"/>
        <mapping class="com.vy.entities.Post"/>
        <mapping resource="config/Users.hbm.xml"/>      
        <mapping resource="config/Post.hbm.xml"/>               
    </session-factory>
</hibernate-configuration>

(Note: Simplest way, if you follow default way, it means put all xml config files inside srcfolder, when build sessionFactory, only:

(注意:最简单的方式,如果你遵循默认方式,这意味着将所有 xml 配置文件放在src文件夹中,在构建 sessionFactory 时,只需要:

return new Configuration().configure().buildSessionFactory();

)

)

回答by Zvonimir Lozancic

My problem was that i had a exculding patern in the resorces folder. After removing it the

我的问题是我在 resorces 文件夹中有一个排除模式。去掉之后

config.configure(); 

worked for me. With the structure src/java/...HibernateUtil.java and cfg file under src/resources.

为我工作。使用结构 src/java/...HibernateUtil.java 和 src/resources 下的 cfg 文件。

回答by ?MER TA?CI

Using configure() method two times is responsible the problem for me. Instead of using like this :

两次使用 configure() 方法对我来说是问题所在。而不是像这样使用:

    Configuration configuration = new Configuration().configure();
    configuration.configure("/main/resources/hibernate.cfg.xml");

Now, I am using like this, problem does not exist anymore.

现在,我是这样使用的,问题不再存在。

    Configuration configuration = new Configuration();
    configuration.configure("/main/resources/hibernate.cfg.xml");

P.S: My hibernate.cfg.xml file is located at "src/main/resources/hibernate.cfg.xml",too. The code belove works for me. at hibernate-5

PS:我的 hibernate.cfg.xml 文件也位于“src/main/resources/hibernate.cfg.xml”。代码 belove 对我有用。在 hibernate-5

public class HibernateUtil {

 private static SessionFactory sessionFactory ;


 static {
     try{
    Configuration configuration = new Configuration();
    configuration.configure("/main/resources/hibernate.cfg.xml");
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(builder.build());
 }
     catch(Exception e){
         e.printStackTrace();
     }
     }

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
}  

回答by Manoj Majumdar

In case of a Maven Project, create a folder named resources under src/main folder and add the resources folder as a source folder in your classpath.

如果是 Maven 项目,请在 src/main 文件夹下创建一个名为 resources 的文件夹,并将资源文件夹添加为类路径中的源文件夹。

You can do that by going to Configure Build Path and then clicking Add Folder to the Sources Tab.

您可以通过转到配置构建路径,然后单击将文件夹添加到源选项卡来完成此操作。

Then check the resources folder and click Apply.

然后检查资源文件夹并单击应用。

Then just use :

然后只需使用:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

回答by Quan VO

For anyone interested: if you are using Intellj, just simply put hibernate.cfg.xmlunder src/main/resources.

对于任何人感兴趣的是:如果你正在使用Intellj,只是简单地说hibernate.cfg.xmlsrc/main/resources