Hibernate与H2数据库无法在netbeans中工作

时间:2015-12-08 23:09:25

标签: java hibernate jpa netbeans

我无法通过非常简单的代码让Hibernate在netbeans上使用H2数据库。请帮忙!我收到这个错误:

Testcase: initializationError(Teste):   Caused an ERROR
org/hamcrest/SelfDescribing
java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
Caused by: java.lang.ClassNotFoundException: org.hamcrest.SelfDescribing
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

以下是文件的内容:

hibernate.cfg.xml中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">org.h2.Driver</property>
    <property name="hibernate.connection.url">jdbc:h2:./testeDB</property>
    <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
  </session-factory>
</hibernate-configuration>

的persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="HibernateAgoraVaiPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>Pessoa</class>
    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:h2:./testeDB"/>
      <property name="javax.persistence.jdbc.user" value=""/>
      <property name="javax.persistence.jdbc.password" value=""/>
      <property name="dialect" value="org.hibernate.dialect.H2Dialect" />
      <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
    </properties>
  </persistence-unit>
</persistence>

Pessoa.java

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class Pessoa implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    @Column(length=50, nullable=false)
    private String nome;

    @Temporal(TemporalType.DATE)
    private Date aniversario;

    public Pessoa(){
    }

    public Date getAniversario() {
        return this.aniversario;
    }

    public void setAniversario(Date aniversario) {
        this.aniversario = aniversario;
    }

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNome() {
        return this.nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }
}

Teste.java

import java.util.Collection;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import org.junit.Test;


public class Teste {
    private EntityManager em;

    public Teste(){
        this.em = Persistence.createEntityManagerFactory("TesteHibernatePU").createEntityManager();
    }

    @Test
    public void inserir(){
        // Instanciamos um objeto Pessoa, setando nome e data de nascimento
        Pessoa p1 = new Pessoa();
        p1.setNome("Jonnas Fonini");
        p1.setAniversario(new Date());

        Pessoa p2 = new Pessoa();
        p2.setNome("Luana Fonini");
        p2.setAniversario(new Date());

        Pessoa p3 = new Pessoa();
        p3.setNome("Fulano de Tal");
        p3.setAniversario(new Date());

        // Iniciamos a transação
        em.getTransaction().begin();
        // Aqui persistimos os objetos recém criados
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        // E aqui efetuamos definitivamente a transação
        em.getTransaction().commit();
    }

    @Test
    public void listar(){
        Collection <Pessoa> lista = em.createQuery("from Pessoa").getResultList();

        for (Pessoa p : lista){
            System.out.println(p.getId() + " – " + p.getNome() + " – " + p.getAniversario());
        }
    }
}

以下是我的步骤:

1)在NetBeans(版本8.1)

中创建了一个新项目

2)在项目中添加了Hibernate库:右键单击库&gt;添加库...&gt;导入&gt; Hibernate 4.3.x

3)从此链接下载最新稳定版H2 http://repo2.maven.org/maven2/com/h2database/h2/1.3.176/h2-1.3.176.jar并将jar添加为库:右键单击库&gt;添加JAR /文件夹&gt;选择下载的JAR文件

4)在“服务”选项卡中创建新的数据库连接:右键单击数据库&gt;新连接...&gt;选择新的驱动程序选项&gt;挑选在步骤(3)下载的JAR文件&gt; OK和Next>左用户名和密码为空,只是通知“jdbc:h2:./ testeDB”(没有引号)作为JDBC URL,并成功测试连接&gt;选择PUBLIC SCHEMA和Finished

5)使用助手创建了一个新的Hibernate配置:右键单击“source-code packages”&gt;新&gt;其他&gt; Hibernate&gt;助手&gt;接下来,选择在步骤(4)

上创建的连接

6)创建一个新的持久性单元:右键单击“源代码包”&gt;新&gt;其他&gt;持久性&gt; <持久性单元>下一个&gt;将持久性库更改为Hibernate JPA 2.1,将数据库连接更改为在步骤(4)中创建的连接,并将表策略更改为

之后我编辑了persistence.xml和hibernate.cfg.xml以使用org.hibernate.dialect.H2Dialect

最后我创建了一个简单的Person类和一些测试代码。还使用

授予项目文件夹的完全权限
sudo chmod 777 -R HibernateAgoraVai

因为我可能是创建数据库文件的权限问题..

1 个答案:

答案 0 :(得分:0)

我发现代码存在以下问题。虽然可以帮助任何人:

1)正如gauee所指出的那样,我应该将hamcrest-core-1.3.jar下载并添加到测试库中。

2)在createEntityManagerFactory调用中,我传递了“TesteHibernatePU”。这必须与persistence.xml中使用的名称相同,在本例中为“HibernateAgoraVaiPU”

3)另一个图书馆遗失了。似乎是JUnit 4.11及更高版本的依赖项。不得不下载jandex-1.1.0.Final.jar并将其添加到测试库中。

4)最后我不得不将Hibernate表策略创建从“Create”更改为“Drop and create”。我还是不明白为什么要做这个改变。