Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法从/hibernate.cfg.xml加载配置_Java_Mysql_Hibernate - Fatal编程技术网

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

Java 无法从/hibernate.cfg.xml加载配置,java,mysql,hibernate,Java,Mysql,Hibernate,我有一个使用Hibernate的web项目。项目结构为: src | |--java | |--com.rusakov... | |--resources | |--hibernate.cfg.xml | |--webapp |--WEB-INF 我的hibernate.cfg.xml如下所示: <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD

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

src
|
|--java
|    |--com.rusakov...
|
|--resources
|    |--hibernate.cfg.xml
|
|--webapp
     |--WEB-INF
我的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>
实体
类别:

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

    public UserEnt() {};

    //** setters and getters **//
}
当我试图将
用户
对象保存到数据库时,我得到以下信息:

INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
org.hibernate.HibernateException: /hibernate.cfg.xml not found
我调用
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();
    }
}

我做错了什么?

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

尝试将您的
hibernate.cfg.xml
移动到
**/WEB-INF/classes/

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

编辑

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

    Configuration configuration = new Configuration();
    configuration.configure(Paths.get("/full","path","to","hibernate","config", "hibernate.cfg.xml").toFile());
假设绝对路径为:

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

以下是解决您问题的方法:它对我的项目有效

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

Assessment
项目中的
hibernate.cfg.xml
文件的图像

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

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

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

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

BaseSessionFactory.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;
}
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());
            }
        }
    }

}
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;
}
对于打开的hibernate连接,请在中调用
getCurrentSession()
方法

loginbussience.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;
}
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());
            }
        }
    }

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


最后,您将从
Users
pojo类

中获得该用户的名称。我已将其移动了很多次,但仍有此问题。当我在configuration.configure()中写入此文件的绝对路径时,它也不起作用;我真的不知道为什么,但是当我部署我的应用程序时,hibernate.cfg.xml没有放到输出文件夹中