会话工厂在Hibernate中返回为null。

huangapple 未分类评论61阅读模式
标题翻译

SessionFactory returning null in Hibernate

问题

我是Hibernate的初学者在创建`SessionFactory`时遇到了问题

**SessionFactoryProvider.java**

```java
public class SessionFactoryProvider {

    private static SessionFactory factory;

    public static SessionFactory getFactory() {

        try {
            if (factory == null) {
                Configuration cfg = new Configuration().configure("hibernate.cfg.xml");

                factory = cfg.buildSessionFactory();
            }
        } catch (Exception e) {
            try {
                if (factory == null) {
                    Configuration configuration = new Configuration();
                    // Hibernate设置与hibernate.cfg.xml中的属性等效
                    Properties property = new Properties();
                    property.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
                    property.put(Environment.URL, "jdbc:mysql://localhost:3306/shopingsite");
                    property.put(Environment.USER, "root");
                    property.put(Environment.PASS, "");
                    property.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
                    property.put(Environment.SHOW_SQL, "true");
                    property.put(Environment.HBM2DDL_AUTO, "update");
                    property.put(Environment.POOL_SIZE, 12);
                    configuration.setProperties(property);
                    configuration.addAnnotatedClass(Category.class);
                    configuration.addAnnotatedClass(User.class);
                    configuration.addAnnotatedClass(Product.class);

                    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                            .applySettings(configuration.getProperties()).build();
                    factory = configuration.buildSessionFactory(serviceRegistry);

                }
            } catch (HibernateException | NullPointerException he) {
                System.out.println("Both factory code Fail");
            }
        }

        return factory;
    }

    public static void shutdow() {
        factory.close();
    }
}

pom.xml:

<!-- 在这里是pom.xml的内容 -->

hibernate.cfg.xml:

<!-- 在这里是hibernate.cfg.xml的内容 -->

日志中显示的错误如下:

Info:   MavenShopping was successfully deployed in 1,530 milliseconds.
Info:   1
Info:   HHH000412: Hibernate Core {5.4.6.Final}
Info:   ******************************************
Info:   HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
WARN:   HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Info:   HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/shopingsite]
Info:   HHH10001001: Connection properties: {user=root, password=****, autocommit=true}
Info:   HHH10001003: Autocommit mode: true
Warning:   StandardWrapperValve[RegistrationServlet]: Servlet.service() for servlet RegistrationServlet threw exception
java.lang.NoSuchMethodError: org.hibernate.internal.CoreMessageLogger.debugf(Ljava/lang/String;I)V

如何解决这个问题?


<details>
<summary>英文翻译</summary>

I am beginner in Hibernate and facing problem in creation of `SessionFactory`,

**SessionFactoryProvider.java :** 

    public class SessionFactoryProvider {
    
        private static SessionFactory factory;
    
        public static SessionFactory getFactory() {
    
            try {
                if (factory == null) {
                    Configuration cfg = new Configuration().configure(&quot;hibernate.cfg.xml&quot;);
    
                    factory = cfg.buildSessionFactory();
                }
            } catch (Exception e) {
                try {
                    if (factory == null) {
                        Configuration configuration = new Configuration();
                        // Hibernate settings equivalent to hibernate.cfg.xml&#39;s properties
                        Properties property = new Properties();
                        property.put(Environment.DRIVER, &quot;com.mysql.jdbc.Driver&quot;);
                        property.put(Environment.URL, &quot;jdbc:mysql://localhost:3306/shopingsite&quot;);
                        property.put(Environment.USER, &quot;root&quot;);
                        property.put(Environment.PASS, &quot;&quot;);
                        property.put(Environment.DIALECT, &quot;org.hibernate.dialect.MySQL5Dialect&quot;);
                        property.put(Environment.SHOW_SQL, &quot;true&quot;);
                        property.put(Environment.HBM2DDL_AUTO, &quot;update&quot;);
                        property.put(Environment.POOL_SIZE, 12);
                        configuration.setProperties(property);
                        configuration.addAnnotatedClass(Category.class);
                        configuration.addAnnotatedClass(User.class);
                        configuration.addAnnotatedClass(Product.class);
    
                        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                                .applySettings(configuration.getProperties()).build();
                        factory = configuration.buildSessionFactory(serviceRegistry);
               
                    }
                } catch (HibernateException | NullPointerException he) {
                    System.out.println(&quot;Both factory code Fail&quot;);
                }
            }
    
            return factory;
        }
    
        public static void shutdow() {
            factory.close();
        }
    }
    

**pom.xml :**
    
    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
    &lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
            &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
        
            &lt;groupId&gt;com.mycompany&lt;/groupId&gt;
            &lt;artifactId&gt;MavenShopping&lt;/artifactId&gt;
            &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
            &lt;packaging&gt;war&lt;/packaging&gt;
        
            &lt;name&gt;MavenShopping&lt;/name&gt;
        
            &lt;properties&gt;
                &lt;endorsed.dir&gt;${project.build.directory}/endorsed&lt;/endorsed.dir&gt;
                &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
            &lt;/properties&gt;
        
            &lt;build&gt;
                &lt;plugins&gt;
                    &lt;plugin&gt;
                        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                        &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
                        &lt;version&gt;3.1&lt;/version&gt;
                        &lt;configuration&gt;
                            &lt;source&gt;1.7&lt;/source&gt;
                            &lt;target&gt;1.7&lt;/target&gt;
                            &lt;compilerArguments&gt;
                                &lt;endorseddirs&gt;${endorsed.dir}&lt;/endorseddirs&gt;
                            &lt;/compilerArguments&gt;
                        &lt;/configuration&gt;
                    &lt;/plugin&gt;
                    &lt;plugin&gt;
                        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                        &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt;
                        &lt;version&gt;2.6&lt;/version&gt;
                        &lt;configuration&gt;
                            &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt;
                        &lt;/configuration&gt;
                    &lt;/plugin&gt;
                    &lt;plugin&gt;
                        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                        &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;
                        &lt;version&gt;2.6&lt;/version&gt;
                        &lt;executions&gt;
                            &lt;execution&gt;
                                &lt;phase&gt;validate&lt;/phase&gt;
                                &lt;goals&gt;
                                    &lt;goal&gt;copy&lt;/goal&gt;
                                &lt;/goals&gt;
                                &lt;configuration&gt;
                                    &lt;outputDirectory&gt;${endorsed.dir}&lt;/outputDirectory&gt;
                                    &lt;silent&gt;true&lt;/silent&gt;
                                    &lt;artifactItems&gt;
                                        &lt;artifactItem&gt;
                                            &lt;groupId&gt;javax&lt;/groupId&gt;
                                            &lt;artifactId&gt;javaee-endorsed-api&lt;/artifactId&gt;
                                            &lt;version&gt;7.0&lt;/version&gt;
                                            &lt;type&gt;jar&lt;/type&gt;
                                        &lt;/artifactItem&gt;
                                    &lt;/artifactItems&gt;
                                &lt;/configuration&gt;
                            &lt;/execution&gt;
                        &lt;/executions&gt;
                    &lt;/plugin&gt;
                &lt;/plugins&gt;
            &lt;/build&gt;
            &lt;dependencies&gt;
                &lt;dependency&gt;
                    &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
                    &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
                    &lt;version&gt;5.4.6.Final&lt;/version&gt;
                    &lt;type&gt;jar&lt;/type&gt;
                &lt;/dependency&gt;
                &lt;dependency&gt;
                    &lt;groupId&gt;mysql&lt;/groupId&gt;
                    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
                    &lt;version&gt;5.1.16&lt;/version&gt;
                &lt;/dependency&gt;
                &lt;dependency&gt;
                    &lt;groupId&gt;javax&lt;/groupId&gt;
                    &lt;artifactId&gt;javaee-web-api&lt;/artifactId&gt;
                    &lt;version&gt;8.0&lt;/version&gt;
                    &lt;type&gt;jar&lt;/type&gt;
                &lt;/dependency&gt;
            &lt;/dependencies&gt;
        &lt;/project&gt;

**hibernate.cfg.xml**


    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
    &lt;!DOCTYPE hibernate-configuration PUBLIC &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot; &quot;http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd&quot;&gt;
    &lt;hibernate-configuration&gt;
      &lt;session-factory&gt;
        &lt;property name=&quot;hibernate.hbm2ddl.auto&quot;&gt;update&lt;/property&gt;
        &lt;property name=&quot;hibernate.dialect&quot;&gt;org.hibernate.dialect.MySQL5Dialect&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.url&quot;&gt;jdbc:mysql://localhost:3306/shopingsite&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.username&quot;&gt;root&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.password&quot;/&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.autocommit&quot;&gt;true&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt;
        &lt;mapping class=&quot;BeanFile.Category&quot;/&gt;
        &lt;mapping class=&quot;BeanFile.Product&quot;/&gt;
        &lt;mapping class=&quot;BeanFile.User&quot;/&gt;
      &lt;/session-factory&gt;
    &lt;/hibernate-configuration&gt;

Error which was showing in the log is shown below
  

    Info:   MavenShopping was successfully deployed in 1,530 milliseconds.
    Info:   1
    Info:   HHH000412: Hibernate Core {5.4.6.Final}
    Info:   ******************************************
    Info:   HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
    WARN:   HHH10001002: Using Hibernate built-in connection pool (not for production use!)
    Info:   HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/shopingsite]
    Info:   HHH10001001: Connection properties: {user=root, password=****, autocommit=true}
    Info:   HHH10001003: Autocommit mode: true
    Warning:   StandardWrapperValve[RegistrationServlet]: Servlet.service() for servlet RegistrationServlet threw exception
    java.lang.NoSuchMethodError: org.hibernate.internal.CoreMessageLogger.debugf(Ljava/lang/String;I)V


How to solve this ?





</details>


# 答案1
**得分**: 0

你的[Hibernate SessionFactory][1]存在问题,与你的环境有关。看起来你的编译时库与运行时库不一致,因为在编码时使用的某个类的方法在服务器启动时不存在。

    java.lang.NoSuchMethodError: org.hibernate.internal.CoreMessageLogger.debugf(Ljava/lang/String;I)V

这似乎是导致[SessionFactory创建][2]出现问题的主要原因。


  [1]: https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/3-ways-to-build-a-Hibernate-SessionFactory-in-Java-by-example
  [2]: https://www.youtube.com/watch?v=Fo11opVImo8

<details>
<summary>英文翻译</summary>

The problem with your [Hibernate SessionFactory][1] has something to do with your environment. It would appear that your compile time libraries are not the same as your runtime libraries, as a method on one of the classes you use when coding isn&#39;t there when the server kicks off.

    java.lang.NoSuchMethodError: org.hibernate.internal.CoreMessageLogger.debugf(Ljava/lang/String;I)V

That seems to be the big problem triggering issues with [SessionFactory creation][2].


  [1]: https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/3-ways-to-build-a-Hibernate-SessionFactory-in-Java-by-example
  [2]: https://www.youtube.com/watch?v=Fo11opVImo8

</details>



huangapple
  • 本文由 发表于 2020年5月30日 20:30:21
  • 转载请务必保留本文链接:https://java.coder-hub.com/62102466.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定