2012-11-18 40 views
0

我正在關注Hibernate的this教程。該教程已經很老了,因爲它仍然使用舊的buildSessionFactory()。buildSessionFactory在Hibernate中的替代

我的問題是我將如何使用最新的buildSessionFactory(serviceRegistry)我是hibernate的新手。我不知道我將如何實現這一點。這是我的代碼

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教程,它真的會有所幫助。

+0

我不喜歡沒有Maven的Hibernate(或其他依賴管理工具)。聽起來很容易出錯並且很費時間,特別是如果你在學習。 –

+0

@Alex所以你建議我在學習Hibernate時使用Hibernate和Maven? – user962206

+0

我當然會那樣做。這意味着您不會遇到不匹配/缺失依賴關係的問題。它會讓整個體驗變得更加輕鬆,並且是以後的好習慣。當你開始一個更大的項目時,你不會想要手動處理你的依賴關係。 –

回答

1

看來你是Hibernate的新手,並且正在爲其基礎而努力。我建議你閱讀文檔並學習這個概念。

Hibernate Documentation是理解一些基礎知識的好起點。

另外我寫了series of articles on Hibernate你可能想要通過。

而對於編程訪問SessionFactory的,我建議你使用以下Hibernate工具類在本教程中給出:

Hibernate Hello World example

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

希望這會有所幫助。

相關問題