Java Hibernate 简单示例中的错误初学者级别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18706646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:21:23  来源:igfitidea点击:

Error in Hibernate simple example Beginner level

javahibernate

提问by Eric

In order to learn hibernate, I write two examples for practising. However, both of them have same error as following:

为了学习hibernate,我写了两个例子来练习。但是,它们都具有以下相同的错误:

Failed to create sessionFactory object.java.lang.NoClassDefFoundError: javax/transaction/SystemException Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.NoClassDefFoundError: javax/transaction/SystemException at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at org.jboss.logging.Logger.getMessageLogger(Logger.java:2248) at org.jboss.logging.Logger.getMessageLogger(Logger.java:2214) at org.hibernate.cfg.Configuration.(Configuration.java:184) at com.example.ManageEmployee.main(ManageEmployee.java:17)

无法创建 sessionFactory object.java.lang.NoClassDefFoundError: javax/transaction/SystemException 异常在线程“main” java.lang.ExceptionInInitializerError 引起的:java.lang.NoClassDefFoundError: javax/transaction/SystemException at java.lang.Class.forName0 (Native Method) at java.lang.Class.forName(Unknown Source) at org.jboss.logging.Logger.getMessageLogger(Logger.java:2248) at org.jboss.logging.Logger.getMessageLogger(Logger.java:2214)在 org.hibernate.cfg.Configuration.(Configuration.java:184) 在 com.example.ManageEmployee.main(ManageEmployee.java:17)

Basically, I write POJO first, and using eclipse generates hbm.xml. After than, I write main function to manage the database. I tried twice but got same problem.

基本上我先写POJO,用eclipse生成hbm.xml。之后,我编写了main函数来管理数据库。我尝试了两次,但遇到了同样的问题。

Could someone give me advice to solve this problem? Before that, using JDBC builds a project, but that is too complex. So I need to learn hibernate. Thank you.

有人可以给我建议来解决这个问题吗?在此之前,使用JDBC构建一个项目,但那太复杂了。所以我需要学习hibernate。谢谢你。

Supplement(detail in this hibernate example project):

补充(此休眠示例项目中的详细信息):

  1. My Eclipse project Name: HibernateExa
  2. hibernate.cfg.xml:

    <session-factory>
    
        <!-- hibernate dialect -->
    
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">hibernateTest</property>
    
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetest;</property>
        <property name="hibernate.connection.username">hibernater</property>
        <property name="hibernate.default_schema">hibernatetest</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    
        <!-- Automatic schema creation(begin) -->
        <property name="hibernate.hbm2ddl.auto">create</property>
        <!-- Simple memory-only cache -->
        <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
    
        <!-- mapping files with external dependencies -->
        <mapping resource="com/sample/Person.hbm.xml"/>
    
    
    </session-factory>
    

  3. My POJO is Person.java. Using eclipse generates Person.hbm.xml.

  4. Project contains main function: TestPerson.java

    public static void main(String [] args){
    
        Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
    
        session.beginTransaction();
    
        createPerson(session);
        queryPerson(session);
    
    }
    
    public static void createPerson(Session session){
        Person person = new Person();
    
        person.setName("Hyman");
        person.setSurname("Yu");
        person.setAddress("White House");
    
        session.save(person);
    }
    
    private static void queryPerson(Session session){
        Query query = session.createQuery("from person");
        List<Person> list = new ArrayList<Person>();
        list = query.list();
        java.util.Iterator<Person> iter = list.iterator();
    
        while(iter.hasNext()){
            Person person = iter.next();
            System.out.println("Person: \"" + person.getName() + "\", "+ person.getSurname() + "\", "
                    + person.getAddress());
        }
    
        session.getTransaction().commit();
    }
    
  5. Here is error info:

    Initial SessionFactory creation failed. java.lang.NoClassDefFoundError: javax/persistence/EntityListeners Exception in thread "main" java.lang.ExceptionInInitializerError at com.sample.SessionFactoryUtil.(SessionFactoryUtil.java:17) at com.sample.TestPerson.main(TestPerson.java:14) Caused by: java.lang.NoClassDefFoundError: javax/persistence/EntityListeners at org.hibernate.cfg.annotations.reflection.JPAMetadataProvider.getDefaults(JPAMetadataProvider.java:97) at org.hibernate.annotations.common.reflection.java.JavaReflectionManager.getDefaults(JavaReflectionManager.java:226) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1331) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840) at com.sample.SessionFactoryUtil.(SessionFactoryUtil.java:13) ... 1 more Caused by: java.lang.ClassNotFoundException: javax.persistence.EntityListeners at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 7 more

  1. 我的 Eclipse 项目名称:HibernateExa
  2. hibernate.cfg.xml:

    <session-factory>
    
        <!-- hibernate dialect -->
    
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">hibernateTest</property>
    
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetest;</property>
        <property name="hibernate.connection.username">hibernater</property>
        <property name="hibernate.default_schema">hibernatetest</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    
        <!-- Automatic schema creation(begin) -->
        <property name="hibernate.hbm2ddl.auto">create</property>
        <!-- Simple memory-only cache -->
        <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
    
        <!-- mapping files with external dependencies -->
        <mapping resource="com/sample/Person.hbm.xml"/>
    
    
    </session-factory>
    

  3. 我的 POJO 是Person.java。使用 eclipse 生成Person.hbm.xml

  4. 项目包含主要功能:TestPerson.java

    public static void main(String [] args){
    
        Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
    
        session.beginTransaction();
    
        createPerson(session);
        queryPerson(session);
    
    }
    
    public static void createPerson(Session session){
        Person person = new Person();
    
        person.setName("Hyman");
        person.setSurname("Yu");
        person.setAddress("White House");
    
        session.save(person);
    }
    
    private static void queryPerson(Session session){
        Query query = session.createQuery("from person");
        List<Person> list = new ArrayList<Person>();
        list = query.list();
        java.util.Iterator<Person> iter = list.iterator();
    
        while(iter.hasNext()){
            Person person = iter.next();
            System.out.println("Person: \"" + person.getName() + "\", "+ person.getSurname() + "\", "
                    + person.getAddress());
        }
    
        session.getTransaction().commit();
    }
    
  5. 这是错误信息:

    初始 SessionFactory 创建失败。java.lang.NoClassDefFoundError: javax/persistence/EntityListeners Exception in thread "main" java.lang.ExceptionInInitializerError at com.sample.SessionFactoryUtil.(SessionFactoryUtil.java:17) at com.sample.TestPerson.main(TestPerson.java:14) ) 引起:java.lang.NoClassDefFoundError: javax/persistence/EntityListeners at org.hibernate.cfg.annotations.reflection.JPAMetadataProvider.getDefaults(JPAMetadataProvider.java:97) at org.hibernate.annotations.common.reflection.java.JavaReflectionManager .getDefaults(JavaReflectionManager.java:226) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1331) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1756) at org.hibernate.cfg。 Configuration.buildSessionFactory(Configuration.java:

Basically, this example could help me to practise how to using hibernate. Nevertheless, I got problem at the very beginning that create the project.

基本上,这个例子可以帮助我练习如何使用休眠。尽管如此,我在创建项目的一开始就遇到了问题。

Hopefully, I could solve this problem soon. Please some advice, Thank you.

希望我能尽快解决这个问题。请给点建议,谢谢。

采纳答案by Ima Miri

Please make sure you have all of this jar files in your lib folder:

请确保您的 lib 文件夹中有所有这些 jar 文件:

lib/antlr.jar
lib/cglib.jar
lib/asm.jar
lib/commons-collections.jar
lib/commons-logging.jar
lib/jta.jar
lib/dom4j.jar
lib/log4j.jar
lib/hibernate3.jar

回答by Eric

Problem is solved! Thanks for everyone's advice.

问题解决了!谢谢大家的建议。

So I summary the issue and give the solution.

所以我总结了这个问题并给出了解决方案。

ERROR: Initial SessionFactory creation failed. java.lang.NoClassDefFoundError. some jar files are misssing.

错误:初始 SessionFactory 创建失败。java.lang.NoClassDefFoundError。缺少一些 jar 文件。

In order to set hibernate project, here is the list for jar files:

为了设置休眠项目,这里是 jar 文件的列表:

enter image description here

在此处输入图片说明

  1. Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: person is not mapped [from person] Because hibernate query is based on Object, from person should be from Person.
  2. The correct connection url:

    jdbc:mysql://localhost:3306/hibernatetest?useUnicode=true&characterEncoding=GBK

  3. In DB, the id is INT. However, in Person.hbm.xml I change id type to "long". Thus, the expected result comes out.

  1. 线程“main”中的异常 org.hibernate.hql.ast.QuerySyntaxException:person 未映射 [from person] 因为休眠查询是基于 Object 的,所以 from person 应该来自 Person。
  2. 正确的连接网址:

    jdbc:mysql://localhost:3306/hibernatetest?useUnicode=true&characterEncoding=GBK

  3. 在 DB 中,id 是 INT。但是,在 Person.hbm.xml 中,我将 id 类型更改为“long”。这样,预期的结果就出来了。

回答by Sai prateek

Add this dependency in your pom.xml

在您的 pom.xml 中添加此依赖项

<dependency>
   <groupId>javax.transaction</groupId>
   <artifactId>jta</artifactId>
   <version>1.1</version>
</dependency>

Make a mvn clean installand deploy.

制作mvn clean install并部署。

Another way:
Download this jar: Project -->right click --> build path --> add external jar

另一种方式:
下载这个jar:项目-->右键单击-->构建路径-->添加外部jar

Project-->right click -->properties --> deployment assembly --> add --> add from build path entries (add this jar)

项目-->右键单击-->属性-->部署程序集-->添加-->从构建路径条目添加(添加这个jar)

Now re build the project.

现在重新构建项目。

Hope it will help.

希望它会有所帮助。

回答by Amit Mishra

Place below dependency inside your pom.xml or add persistence-api jar in your classpath.

将下面的依赖项放在 pom.xml 中或在类路径中添加 persistence-api jar。

<dependency>
   <groupId>javax.persistence</groupId>
   <artifactId>persistence-api</artifactId>
   <version>1.0</version>
</dependency>