【问题标题】:How can I create a Hibernate session without hiberante.cfg.xml file?如何在没有 hibernate.cfg.xml 文件的情况下创建 Hibernate 会话?
【发布时间】:2026-01-17 17:50:01
【问题描述】:

这是我第一次使用Hiberante

我正在尝试使用以下内容在我的应用程序中创建 Hibernate session

Session session = HiberanteUtil.getSessionFactory().openSession();

它给了我这个错误:

org.hibernate.HibernateException: /hibernate.cfg.xml not found

但是我的项目中没有hibernate.cfg.xml 文件。

如何在没有此文件的情况下创建会话

【问题讨论】:

标签: java hibernate hibernate.cfg.xml


【解决方案1】:
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.concretepage.persistence.User;

public class HibernateUtil {
    private static final SessionFactory concreteSessionFactory;
    static {
        try {
            Properties prop= new Properties();
            prop.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
            prop.setProperty("hibernate.connection.username", "root");
            prop.setProperty("hibernate.connection.password", "");
            prop.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");

            concreteSessionFactory = new AnnotationConfiguration()
           .addPackage("com.concretepage.persistence")
                   .addProperties(prop)
                   .addAnnotatedClass(User.class)
                   .buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static Session getSession()
            throws HibernateException {
        return concreteSessionFactory.openSession();
    }

    public static void main(String... args){
        Session session=getSession();
        session.beginTransaction();
        User user=(User)session.get(User.class, new Integer(1));
        System.out.println(user.getName());
        session.close();
    }
    }

【讨论】:

  • 谢谢,您是否推荐这种方式而不是其他 hibernate.cfg.xml?
  • 我对这意味着什么感到困惑:import com.concretepage.persistence.User; ?
  • @java123999 这是你的持久类。您可以使用带有 @Entity@Table 注释的任何类。
  • 嗨,java123999 import com.concretepage.persistence.User 是我的 POJO 类。你可以导入你的 POJO。这样可以避免xml文件。
  • AnnotationConfiguration 从 Hibernate 5 中删除
【解决方案2】:

配置 Hibernate 4 或 Hibernate 5 的简单方法

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

Hibernate 从 hibernate.cfg.xmlhibernate.properties 读取配置。

如果您不想阅读hibernate.cfg.xml,则不应致电configure()。添加带注释的类

SessionFactory sessionFactory = new Configuration()
    .addAnnotatedClass(User.class).buildSessionFactory();

【讨论】:

    最近更新 更多