java 无法从 /hibernate.cfg.xml 加载配置

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

Cannot load configuration from /hibernate.cfg.xml

javamysqlhibernate

提问by Valerii Rusakov

I have a web project where I am using Hibernate. Structure of project is:

我有一个使用 Hibernate 的 Web 项目。项目结构为:

src
|
|--java
|    |--com.rusakov...
|
|--resources
|    |--hibernate.cfg.xml
|
|--webapp
     |--WEB-INF

My hibernate.cfg.xml looks like:

我的 hibernate.cfg.xml 看起来像:

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/computersdb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">34902</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">update</property>

    <mapping package="com.rusakov.entities"/>
  </session-factory>
</hibernate-configuration>

My class for initialization of SessionFactory:

我的初始化类SessionFactory

public class HibernateUtil {
    private static SessionFactory sessionFactory = null;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                Configuration configuration = new Configuration();
                configuration.configure();
                ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()
                        .applySettings(configuration.getProperties());
                sessionFactory = configuration
                        .buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());
            } catch (HibernateException e) {
                e.printStackTrace();
            }
        }
        return sessionFactory;
    }
}

Entityclass:

Entity班级:

public class UserEnt {
    private int id;
    private String login;
    private String password;
    private String name;
    private String surname;

    public UserEnt() {};

    //** setters and getters **//
}

When I am trying to save Userobject to database I am getting this:

当我尝试将User对象保存到数据库时,我得到了这个:

INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
org.hibernate.HibernateException: /hibernate.cfg.xml not found

My class where I call SessionFactory

我打电话的班级 SessionFactory

package com.rusakov.util;

import com.rusakov.entities.*;

import org.hibernate.Session;

public class test {
    public static void main(String[] args) {
        UserEnt user = new UserEnt();
        user.setName("test");
        user.setSurname("test");
        user.setLogin("test");
        user.setPassword("test");
        user.setRole("test");
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();
    }
}

What I am doing wrong?

我做错了什么?

回答by UdayKiran Pulipati

Here is solution for your problem: It works on my project.

这是您问题的解决方案:它适用于我的项目。

Create the hibernate.cfg.xmlfile in root folder of src.

hibernate.cfg.xml在根文件夹中创建文件src

Image of hibernate.cfg.xmlfile in Assessmentproject where to locate.

项目中hibernate.cfg.xml文件的图像Assessment所在位置。

hibernate.cfg.xml location

hibernate.cfg.xml 位置

If you debug the getPath()method you will find the location of the hibernate.cfg.xmlfile in your project.

如果您调试该getPath()方法,您将hibernate.cfg.xml在项目中找到该文件的位置。

SessionFactoryGroceries.java

SessionFactoryGroceries.java

import java.io.File;
import java.net.URI;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionFactoryGroceries extends BaseSessionFactory {
    private static final Logger LOG = Logger.getLogger(SessionFactoryGroceries.class);
    private static final ThreadLocal<Session> THREAD_LOCAL = new ThreadLocal<Session>();
    private static SessionFactory sessionFactory;

private static URI configFile = null;
private static String configFileLocation = "";
private static Configuration configuration = null;
private static Long configurationFileTimestamp = null;

public void getPath() {
    configFileLocation = getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + "hibernate.cfg.xml";
}

/**
 * session factory will be rebuilded in the next call
 * 
 */

public static void setConfigFile(final String configFile) {
    try {
        if (configFile.startsWith("file:"))
            setConfigFile(new URI(configFile));
        else
            setConfigFile(new URI("file:" + configFile));
    } catch (Exception e) {
        LOG.error("Failed to set config file to " + configFile + ": bad URI");
    }
}

public static void setConfigFile(final URI configURI) {
    SessionFactoryGroceries.configFile = configURI;
    sessionFactory = null;
}

/**
 * Returns the ThreadLocal Session instance. Lazy initialize the
 * <code>SessionFactory</code> if needed.
 * 
 * @return Session
 * @throws HibernateException
 */

public static synchronized Session getCurrentSession() {
    SessionFactoryGroceries groceries = new SessionFactoryGroceries();
    groceries.getPath();
    if (didConfigFileChange())
        resetFactory();

    Session session = (Session) THREAD_LOCAL.get();

    if (session == null || !session.isOpen()) {
        if (sessionFactory == null)
            rebuildSessionFactory();

        if (sessionFactory == null)
            session = null;
        else
            session = SessionEx.create(sessionFactory.openSession());

        THREAD_LOCAL.set(session);
    }

    if (session == null)
        throw new RuntimeException("unable to create hibernate session to database.");

    return session;
}

/**
 * Rebuild hibernate session factory
 * 
 */

@SuppressWarnings("deprecation")
public static void rebuildSessionFactory() {
    try {
        LOG.debug("XSpace configuring hibernate from this file: " + configFile);

        File file = new File(configFile);

        if (file.exists() == false)
            throw new RuntimeException("Could not find config file at location: " + configFile);

        configuration = new Configuration();
        configuration.configure(file);
        sessionFactory = configuration.buildSessionFactory();
    } catch (Exception e) {
        LOG.error("%%%% Error Creating SessionFactory %%%%", e);
        e.printStackTrace();
    } catch (Throwable e) {
        LOG.error("%%%% Error Creating SessionFactory %%%%", e);
        e.printStackTrace();
    }
}

private static Boolean didConfigFileChange() {
    if (configFile == null)
        setConfigFile(configFileLocation); // IF NULL USE THE DEFAULT LOCATION.

    File file = new File(configFile);

    if (file.exists() == false)
        throw new RuntimeException("could not find configuration file! " + configFile);

    Boolean changed = Boolean.FALSE;
    Long currentTimestamp = file.lastModified();

    if (configurationFileTimestamp == null) {
        configurationFileTimestamp = currentTimestamp;
    } else {
        if (configurationFileTimestamp.equals(currentTimestamp) == false) {
            configurationFileTimestamp = currentTimestamp;
            changed = true;
        }
    }

    return changed;
}

private static void resetFactory() {
    Session session = (Session) THREAD_LOCAL.get();

    if (session != null) {
        session.close();
    }

    THREAD_LOCAL.set(null);

    final org.hibernate.SessionFactory factory = sessionFactory;

    // wait 10 minutes then close the factory and any open connections on the old factory

    new Thread() {
        public void run() {
            synchronized (this) {
                try {
                    Thread.sleep(1000 * 60 * 10);
                    factory.close();
                } catch (Exception e) {
                    // don't care
                }
            }
        }
    }.start();

    sessionFactory = null;
}

}

}

For Closing the session after getting the data from database.

用于从数据库获取数据后关闭会话。

BaseSessionFactory.java

基会话工厂.java

import org.hibernate.Session;

public class BaseSessionFactory {

    public static void closeSession(final Session session) {
        if (session != null && session.isOpen()) {
            try {
                session.close();
            } catch (Exception e) {
                // LOG.error("Failed to close session: " + e.toString());
            }
        }
    }

}

For open hibernate connection call getCurrentSession()method in

用于打开休眠连接调用getCurrentSession()方法

LoginBussiness.java

登录业务.java

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.grocery.data.hibernate.Users;
import com.grocery.hibernate.SessionFactoryGroceries;

public class LoginBussiness {
    public static final Logger LOG = Logger.getLogger(LoginBussiness.class);

public String usersDetails(Integer loginId, String email, String password) {
    String name = "";
    Session session = null;
    try {
        session = SessionFactoryGroceries.getCurrentSession();
        Criteria criteria = session.createCriteria(Users.class);
        Criterion lhs = Restrictions.eq("userID", loginId);
        Criterion rhs = Restrictions.eq("email", email);
        criteria.add(Restrictions.or(lhs, rhs));
        criteria.add(Restrictions.eq("password", password));
        Users users = (Users) criteria.uniqueResult();
        if (users != null) {
            name = users.getFirstName();
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error("Type of exception occured in userDetails() is --> "+e);
    } finally {
        SessionFactoryGroceries.closeSession(session);
    }
    return name;
}

}

}

finally you will get the name of the user from Userspojo class

最后你会从Userspojo 类中得到用户的名字

回答by nkukhar

Looks like hibernate.cfg.xmlnot under classpath.

看起来hibernate.cfg.xml不在类路径下。

Try to move your hibernate.cfg.xmlto **/WEB-INF/classes/

尝试移动你hibernate.cfg.xml**/WEB-INF/classes/

Create this folder if not exist.

如果此文件夹不存在,则创建此文件夹。

Edit

编辑

For me solution below works perfect

对我来说,下面的解决方案很完美

    Configuration configuration = new Configuration();
    configuration.configure(Paths.get("/full","path","to","hibernate","config", "hibernate.cfg.xml").toFile());

Assuming that absolute path is:

假设绝对路径是:

/full/path/to/file/hibernate/config/hibernate.cfg.xml