实体没有定义主键属性:JPA

时间:2016-11-29 06:07:01

标签: java eclipse jpa java-ee eclipselink

我正在使用Eclipse neon.i我是JPA的新手。我总是得到这个错误。 请帮忙解决这个问题。

下面是我的POJO课程

package myJPA;

import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;


/**
 * The persistent class for the user_online database table.
 * 
 */
@Entity
@Table(name="user_online")
@NamedQuery(name="UserOnline.findAll", query="SELECT u FROM UserOnline u")

public class UserOnline implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name="mem_id")
     @Id
    private int memId;

    @Temporal(TemporalType.TIMESTAMP)
    private Date time;

    public UserOnline() {
    }

    public int getMemId() {
        return this.memId;
    }

    public void setMemId(int memId) {
        this.memId = memId;
    }

    public Date getTime() {
        return this.time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

}  

我的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="myJPA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>myJPA.UserOnline</class>
        <properties>
        </properties>
    </persistence-unit>
</persistence>

当我用这个错误运行我的主类时,我得到了这些错误

Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named Eclipselink_JPA
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
    at myJPA.Main.main(Main.java:13)

Main.java

package myJPA;

import java.sql.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {
public static void main(String[] args) {
    // TODO Auto-generated method stub
     EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );

      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );
      UserOnline u = new UserOnline();
      u.setMemId(999);
      u.setTime(new Date(0));
      entitymanager.persist( u );
      entitymanager.getTransaction( ).commit( );

      entitymanager.close( );
      emfactory.close( );



}

}

1 个答案:

答案 0 :(得分:0)

EntityManagerFactory初始化应更改为:

EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "myJPA" );

您必须提供已定义的持久性单元的名称才能从中创建工厂。