日期:2014-05-20  浏览次数:20684 次

Hibernate注解运行时的错误
Java code


/*
 * 实体类
 */
package com.entity;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.annotations.Entity;

@Entity
public class Weapon {
    private int id;
    private String name;
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}



hibernate配置文件
Java code

<!--添加使用hibernate注解的实体bean,而不是映射文件-->
<mapping class="com/entity/Weapon" />



Java code

package com.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import com.entity.Weapon;

/*
 * 测试类
 * 通过在hibernate文件中注册实体bean,并在实体bean中添加
 * hibernate注解,可以自动创建数据库中的关联表并将属性与字段关联
 */
public class TestAnnotations {
    private static AnnotationConfiguration ac = new AnnotationConfiguration();
    
    private static SessionFactory sf = null;
    
    public static void main(String[] args) {
        ac.configure();
        sf = ac.buildSessionFactory();
        Session session = sf.openSession();
        Transaction tran = session.beginTransaction();
        Weapon weapon = new Weapon();
        weapon.setName("jack");
        session.save(weapon);
        tran.commit();
        session.close();
    }
}


错误信息:
java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager
at com.test.TestAnnotations.<clinit>(TestAnnotations.java:15)
Caused by: java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.ReflectionManager
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
... 1 more
Exception in thread "main" 

jar包一共23个,按着视频的都添加进去了,后添加的两个是:ejb3-persistence.jar和hibernate-annotations.jar


------解决方案--------------------
你代码中引入的是org.hibernate.cfg.AnnotationConfiguration中的jar,但是你定义的时候,系统解析出来你用的是org.hibernate.annotations.common.reflection.ReflectionManager。。。
------解决方案--------------------
探讨
不好意思,没太明白。能说详细点吗?应该引入哪个?

------解决方案--------------------
还有这里。<mapping class="com/entity/Weapon" />
修改成<mapping class="com.entity.Weapon" />