java - 如何在没有 hibernate.cfg.xml 文件的情况下创建 Hibernate session ?

标签 java hibernate hibernate.cfg.xml

这是我第一次使用 Hiberante

我正在尝试使用以下方法在我的应用程序中创建一个 Hibernate session:

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

它给我这个错误:

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

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

没有此文件,我如何创建 session ?

最佳答案

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

关于java - 如何在没有 hibernate.cfg.xml 文件的情况下创建 Hibernate session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35457155/

相关文章:

java - InputStream的read()方法是如何实现的?

java - 多项目 gradle 构建 - java.io.IOException : Unable to delete file

java - tyrus websocket ssl 握手失败

java - 在数据库中搜索文本(使用 Hibernate Search)

java - 使用 JPA hibernate ,连接时间非常慢

nhibernate - 配置 NHibernate hibernate.cfg.xml 文件以拥有更多连接字符串

java - 关于数组列表

java - 错误 : java. lang.NoSuchMethodError : org. objectweb.asm.ClassWriter.<init>(I)V

Java在投影前后在不同模型上使用过滤