suraj kiran suraj kiran - 7 days ago 5
Java Question

entity has no primary key attribute defined : JPA

i am using Eclipse neon.i am new to JPA. i always getting this error.
please help to fix this.

below is my POJO class

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;
}

}


my persistence.xml contents are below

<?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>


when i run my main class with this error i get these errors

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( );



}

}

Answer

EntityManagerFactory initialization should be changed to below :

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

You have to provide name of your defined persistence unit to create factory from it.

Comments