【发布时间】:2016-12-30 11:03:38
【问题描述】:
所以我制作了一个简单的休眠应用程序,并使用 HibernateUtil 静态方法启动了一个提供适当会话的 SessionFactory。
问题是 - 我怎样才能坚持使用此代码?而且我对如何从这个设计中构建以结合 HibernateUtil 来满足我的每个对象需求感到更加困惑?
package com.hibernation.main;
import com.hibernation.model.Animal;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/**
* Created by jonathan on 27/12/16.
*/
public class Earth {
public static void main(String[] args){
Animal a = new Animal(1,"lizard", "gekko", "test");
HibernateUtil();
}
public static void HibernateUtil(){
// create configuration instance and pass in the
// hibernate configuration file.
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
// version 4.x and up, service registry is being used.
// The ServiceRegistry scopes the Service.
// The ServiceRegistry manages the lifecycle of the Service.
// The ServiceRegistry handles injecting dependencies into the Service
// (actually both a pull and a push/injection approach are supported).
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
// create a Session factory instance: session factory creates sessions
// at the request of clients.
// conceptually, this is a single data store that is thread safe.
// should be wrapped in a singleton (HibernateUtil being a common convention)
// the internal state is immutable - once it is created the state is set.
SessionFactory factory = configuration.buildSessionFactory(serviceRegistry);
// get the current session.
Session session = factory.getCurrentSession();
// begin transaction
session.getTransaction().begin();
// Print out all required information
System.out.println("Session Is Opened :: "+ session.isOpen());
System.out.println("Session Is Connected :: "+ session.isConnected());
// commit transaction
session.getTransaction().commit();
}
}
【问题讨论】:
-
你是否在hibernate cfg文件中配置了数据库属性?
-
是的,对数据库的访问正在工作。
-
基本上你需要在 DAO 类中引用 SessionFactory 来持久化对象。为此,您应该编写一个方法来获取 HibernateUtil 类中的 SessionFactory 引用。
-
是的,但是正如peter所指出的——如果我们使用spring&ood原则,我们必须利用IoC容器的使用,并在运行时注入我们的TransactionManager,它可以为我们提供我们的SessionFactory单例实例.有关更多信息,请参阅以下内容docs.spring.io/spring/docs/current/spring-framework-reference/…
标签: java hibernate persistence dao