1

这是我第一次使用Hiberante.

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

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

它给了我这个错误:

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

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

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

4

2 回答 2

4
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();
    }
    }
于 2016-02-17T12:53:27.773 回答
2

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

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

hibernate.cfg.xmlHibernate 从和读取配置hibernate.properties

你不应该打电话configure(),如果你不想读书hibernate.cfg.xml。添加带注释的类

SessionFactory sessionFactory = new Configuration()
    .addAnnotatedClass(User.class).buildSessionFactory();
于 2016-02-17T13:39:31.073 回答