我在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 的教程,那将非常有帮助。
看来你是Hibernate的新手,并且正在为它的基础知识而苦苦挣扎。我建议您浏览文档并学习概念。
Hibernate文档是了解一些基础知识的良好起点。
我还写了一系列关于Hibernate的文章,你可能想通过。
为了以编程方式访问SessionFactory,我建议您使用以下Hibernate实用程序类,如本教程所示:
冬眠你好世界示例
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;
}
希望这有帮助。