package com.util;
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) {
// Make sure you log the exception to track it
System.err.println("SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Optional but can be used to Close caches and connection pools
getSessionFactory().close();
}
}
我正在尝试理解上面的代码。我是 Java 初学者,很难具体理解以下行。这是否意味着 Configuration
对象具有配置方法,并且配置方法具有 buildSessionFactory
方法?
return new Configuration().configure().buildSessionFactory();
最佳答案
方法没有方法,方法返回对象,而这些对象有方法。
这里,Configuration 有一堆返回 Configuration 的方法(因此该方法返回调用它的对象)。这允许方法链接,以便在该对象上调用configure,然后在同一对象上调用buildSessionFactory。
方法链接的一个更常见的示例是 java.lang.StringBuilder 类。您可以在同一构建器对象上通过连续的追加调用来构建字符串:
String example = new StringBuilder(“hello”)
.append(“ “)
.append(“world”)
.toString();
关于Java/Hibernate 初学者问题理解下面的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52250508/