0

我正在关注关于 Hibernate 的本教程。该教程已经很老了,因为它仍然使用旧的 buildSessionFactory()。

我的问题是我将如何使用buildSessionFactory(serviceRegistry)我刚开始休眠的最新版本。我不知道我将如何实现这一点。这是我的代码

public static void main(String[] args) {
    // TODO Auto-generated method stub
    UserDetails ud = new UserDetails();
    ud.setId(1);
    ud.setName("David Jone");

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(serviceRegistry)
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(ud);
    session.getTransaction().commit();

}

如果你们可以在没有 Maven 的情况下链接 Hibernate 4 的教程,那也会很有帮助。

4

1 回答 1

1

看来您是 Hibernate 的新手,并且正在努力学习它的基础知识。我建议您阅读文档并学习该概念。

Hibernate Documentation是了解一些基础知识的良好起点。

此外,我还写了一系列关于 Hibernate 的文章,您可能想阅读这些文章。

对于以编程方式访问 SessionFactory,我建议您使用本教程中给出的以下 Hibernate Utility 类:

休眠 Hello World 示例

package net.viralpatel.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration()
                    .configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

一旦你有了这个类,你可以像这样使用它:

private static Employee save(Employee employee) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = sf.openSession();
    session.beginTransaction();

    Long id = (Long) session.save(employee);
    employee.setId(id);

    session.getTransaction().commit();

    session.close();

    return employee;
}

希望这可以帮助。

于 2012-12-12T12:47:27.900 回答