使用JPA构建Java项目时遇到的问题

时间:2014-02-01 10:49:36

标签: java database jpa entity persistence.xml

我正在尝试运行javax.persistence,但是我得到了错误。 我构建了一个用于测试的小项目,创建了一个实体类,persistence.xml和正在运行的进程:

实体类:

package glasses;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Hund implements Serializable {
    @Id
    private long id;
    private String name;
    private String typ;

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

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

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTyp() {
        return this.typ;
    }

    public void setTyp(String typ) {
        this.typ = typ;
    }
}

的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="GlassesPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/glasses?zeroDateTimeBehavior=convertToNull"/>
      <property name="javax.persistence.jdbc.password" value="mypwd"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
    </properties>
  </persistence-unit>
</persistence>

错误讯息:

Caused by: java.lang.IllegalArgumentException: Object: glasses.Hund@5d2e0422 is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4228)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at glasses.FXMLDocumentController.handleButtonAction(FXMLDocumentController.java:48)
... 54 more

有谁知道这个问题? Hund级有什么不对吗?或者在persistence.xml中?

2 个答案:

答案 0 :(得分:1)

persistence.xml中使用您的Hund课程,如下例所示。只需将它放在属性和持久性单元标记之间。

</properties>
  <class>glasses.Hund</class>
</persistence-unit>

答案 1 :(得分:1)

如果您不想在persistence.xml中列出所有实体,可以在persistence.xml中添加以下行:

<exclude-unlisted-classes>false</exclude-unlisted-classes>