I'm trying to persist elements using JPA and EclipseLink. So I've created a class to persist
#Entity
public class Couple implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "OBJECTID")
private String objectID;
#Column(name = "EPCNUMBER")
private String epcNumber;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
And so on.
I've created a class to "use" that :
public class Main {
private static final String PERSISTENCE_UNIT_NAME = "MyPU";
private static EntityManagerFactory factory;
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
TypedQuery<Couple> q = em.createQuery("SELECT c FROM Couple c", Couple.class);
List<Couple> couples = (List<Couple>) q.getResultList();
And then, i've the following persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="MyPU">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>localJTA</jta-data-source>
<class>fr.mypackage.com.Couple</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.logging.level" value="INFO"/>
</properties>
</persistence-unit>
</persistence>
But, even when I change the properties, I've got the same error :
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named MyPU
(when calling factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);).
Did I do something wrong to ling xml and persistence unit ? I've weel added to classpath the following :
javax.persistence.jar
javax.ejb.jar
eclipselink.jar
javax.persistence_1.0.0.jar
javax.persistence_2.0.4.v201112161009.jar
derby.jar
Could you help me ? Thanks !
On my application, I was having this problem until I compiled my Netbeans project. Then it worked.
Related
hi I'm trying to use JPA with eclipse link but it gives me following error:
I'm using maven, and context.xml file is in web module and persistaence.xml is in access/db module.
Failed to connect to MyModalTestApp: Exception [EclipseLink-30005] (Eclipse
Persistence Services - 2.6.4.v20160829-44060b6):
org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for
persistence archives with ClassLoader: ParallelWebappClassLoader
context: modaltestapp-api
delegate: false
----------> Parent Classloader:
java.net.URLClassLoader#3fee733d
Internal Exception: javax.persistence.PersistenceException: Exception
[EclipseLink-28018] (Eclipse Persistence Services - 2.6.4.v20160829-
44060b6): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [MyModalTestApp]
failed.
Internal Exception: Exception [EclipseLink-7161] (Eclipse Persistence
Services - 2.6.4.v20160829-44060b6):
org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class
com.modaltestapp.entity.RegistrationEntity] has no primary key specified.
It should define either an #Id, #EmbeddedId or an #IdClass. If you have
defined PK using any of these annotations then make sure that you do not
have mixed access-type (both fields and properties annotated) in your
entity class hierarchy.
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="MyModalTestApp" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>java:comp/env/jdbc/MODALTESTAPP_DATASOURCE</non-jta-data-source>
<class>com.modaltestapp.entity.RegistrationEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.ddl-generation" value="none"/>
<property name="eclipselink.weaving" value="static" />
<property name="eclipselink.target-database" value="Auto"/>
<property name="eclipselink.target-server" value="None"/>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="eclipselink.logging.level" value="FINEST"/>
<property name="eclipselink.logging.timestamp" value="true"/>
<property name="eclipselink.logging.session" value="false"/>
<property name="eclipselink.logging.thread" value="true"/>
<property name="eclipselink.logging.exceptions" value="true"/>
<!-- 0 is a valid ID
<property name="eclipselink.id-validation" value="NULL"/> -->
<!-- We need the following, else EclipseLink cannot properly translate column names in Native SQL queries. -->
<property name="eclipselink.jdbc.uppercase-columns" value="true"/>
</properties>
</persistence-unit>
</persistence>
pojo is:
package com.modaltestapp.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "REGISTRATION")
public class RegistrationEntity implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "FIRSTNAME")
private String firstName;
#Column(name = "LASTNAME")
private String lastName;
#Column(name = "LASTNAME")
private String email;
#Column(name = "MESSAGE")
private String message;
#Column(name = "EDUCATION")
private String education;
#Column(name = "HOBBIES")
private String hobbies;
#Column(name = "GENDER")
private String gender;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getHobbies() {
return hobbies;
}
public void setHobbies(String hobbies) {
this.hobbies = hobbies;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
context.xml is:
<Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
<Resource name="jdbc/MODALTESTAPP_DATASOURCE" auth="Container" type="javax.sql.DataSource"
maxTotal="8" maxIdle="2"
username="root" password="unnati#123" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/MODALTESTAPP" validationQuery="select 1"/>
</Context>
and my implementation code is :
try {
EntityManager em = Persistence.createEntityManagerFactory("MyModalTestApp").createEntityManager();
System.out.println("in database portion1");
/* Persist entity */
em.getTransaction().begin();
System.out.println("in database portion2");
em.persist(REG);
System.out.println("in database portion3");
em.getTransaction().commit();
System.out.println("yes transcaction done");
} catch (Exception e) {
System.out.println("Failed to connect to MyModalTestApp: " + e);
// e.printStackTrace();
}
I am trying to store entity Track with children entities TrackPoints with JPA method create. However, to store Track with its children TrackPoints last really long - about 30 seconds. I tried GenerationType.Identity and GenerationType.SEQUENCE. If I also have Hibernate Spatial (Postgis) column, it lasts even longer - about 60 seconds to store parent and all children. JPA sends insert sequentially one followed by another. How can I optimize this? Can anybody tell me what is the main problem?
Technologies:
Wildfly 8.1, JPA 2.1 (hibernate), Hibernate Spatial, EJB, JTA
PostgreSQL 9.3 + PostGis - default setup (just install from Ubuntu package)
Track.java
#Entity
#Table(name = "TRACKS")
public class Track implements Serializable {
#Id
#Column(name = "track_id", nullable = false, unique = true)
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
#NotNull
#NotEmpty
#Size(min = 1, max = 100)
#Column(nullable = false, length = 100)
private String name;
#Size(max = 200)
#Column(nullable = false, length = 200)
private String description;
#OneToOne(optional = false)
#JoinColumn(name = "userId", nullable = false)
private User userOwner;
#NotNull
#NotEmpty
#Column(nullable = false, length = 55)
private String type;
#NotNull
private Boolean isShared;
#OneToMany(mappedBy = "track")
private List<TrackPoint> trackPoints;
}
TrackPoint.java
#Entity
#Table(name = "TRACK_POINTS")
public class TrackPoint implements Serializable {
private static final long serialVersionUID = 8089601593251025235L;
#Id
#Column(name = "trackpoint_id", nullable = false, unique = true)
#GeneratedValue(generator = "track_point_sequence", strategy = GenerationType.SEQUENCE)
#SequenceGenerator(name = "track_point_sequence", sequenceName = "track_point_sequence", allocationSize = 1000)
private Long id;
#NotNull
private int trackSegment;
#NotNull
private double elevation;
#NotNull
#Temporal(TemporalType.TIMESTAMP)
private Date timeStamp;
#NotNull
#ManyToOne(optional = false, fetch = FetchType.EAGER)
#JoinColumn(name = "track_id")
private Track track;
/*Hibernate Spatial - Postgis field.
#NotNull
#Column(nullable = false)
#Type(type = "org.hibernate.spatial.GeometryType")
private Geometry location;*/
}
TrackService.java
#Stateless
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public class TracksService implements ITracksService {
#Inject
private IDaoService dao;
#Override
public Long createTrack(GpxType gpx, String userId, String name, String desc) {
// Map GPX to Track, TrackPoint object.
track = dao.create(track);
int batch_size = 50;
int i = 0;
for(TrackPoint point: track.getTrackPoints()) {
dao.create(point);
if(i++ % batch_size == 0) {
dao.flush();
dao.clear();
}
}
return track.getId();
}
DaoService.java
#Stateless
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public class DaoService implements IDaoService {
#PersistenceContext()
private EntityManager em;
#Override
public <T extends Serializable> T create(T t) {
em.persist(t);
return t;
}
}
persistence.xml
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xsi:schemaLocation=
"http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="postgisTourbookPU" transaction-type="JTA">
<description>PostgresSQL database with PostGIS extension</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>${tourbook.datasource.postgresql.jndi-name}</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<shared-cache-mode>NONE</shared-cache-mode>
<properties>
<!-- JPA properties -->
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create"/>
<!-- <property name="javax.persistence.schema-generation-target"
value="database"/>-->
<!-- Creation Schema Properties -->
<property name="javax.persistence.schema-generation.create-source"
value="metadata"/>
<!-- <!– DDL Script location, when script is used –>
<property name="javax.persistence.schema-generation.create-script-source"
value="META-INF/create-script.sql"/>-->
<!-- Drop Schema Properties -->
<property name="javax.persistence.schema-generation.drop-source"
value="metadata"/>
<!-- <property name="javax.persistence.schema-generation.drop-script-source"
value="META-INF/drop-script.sql"/>-->
<property name="javax.persistence.sql-load-script-source"
value="META-INF/load-script.sql"/>
<!-- JPA driver information -->
<property name="javax.persistence.jdbc.driver"
value="org.postgresql.Driver"/>
<!-- Hibernate properties -->
<property name="hibernate.connection.characterEncoding"
value="UTF-8"/>
<property name="hibernate.dialect"
value="org.hibernate.spatial.dialect.postgis.PostgisDialect"/>
<property name="hibernate.default_schema"
value="public"/>
<property name="hibernate.show_sql"
value="true"/>
<property name="hibernate.jdbc.batch_size" value="50"/>
<property name="hibernate.jdbc.fetch_size"
value="50"/>
<property name="hibernate.order_inserts"
value="true"/>
<property name="hibernate.order_updates"
value="true"/>
<property name="hibernate.cache.use_query_cache"
value="false"/>
<!-- Hibernate caching -->
</properties>
</persistence-unit>
</persistence>
Edited
So I have tried, batch insert in Hibernate, but I still get 30 seconds for saving 2000 points.
you're inserting a parent with all the children. In that case the Hibernate JPA indeed can be slow, but there are a few tips to improve the performance
- check the hibernate batch guide http://docs.jboss.org/hibernate/core/4.0/devguide/en-US/html/ch04.html
- I've used the hibernate.jdbc.batch_size parameter (set to e.g. 50)
Good luck
Gabriel
I have create Entity,DAo and Façade in a Web app. I have no error on my codes but I am getting this exception while using find(T.class,id) method of JPA.An also it says that there is no #Entity annotation on my Entity. But this is not true.How to solve this problem.
MyEntity
#Entity
#Table(name = "uyeler")
public class Uyeler implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "kullaniciadi")
private String kullaniciadi;
#Column(name = "sifre")
private String sifre;
#Column(name = "ad")
private String ad;
#Column(name = "soyad")
private String soyad;
#Column(name = "cinsiyet")
private String cinsiyet;
#Column(name = "ilgialanlari")
private String ilgialanlari;
#Column(name = "dogumtarihi")
private String dogumtarihi;
#Column(name = "eposta")
private String eposta;
#Column(name = "epostahaberdar")
private String epostahaberdar;
public String getKullaniciadi() {
return kullaniciadi;
}
MyDaoImpl;
public abstract class UyelerDaoImpl<T> {
private final static String UNIT_NAME ="KutuphaneOtomasyonuEJB";
#PersistenceUnit(unitName = UNIT_NAME)
private EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory(UNIT_NAME);
private EntityManager em = emf.createEntityManager();
public Uyeler findMemberByUserName(String username){
return em.find(Uyeler.class, username);
}
}
persistence.xml
<persistence-unit name="KutuphaneOtomasyonuEJB"
transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<non-jta-data-source>jdbc/MySQLConnectionPool</non-jta-data-source>
<class>com.mesutemre.businesModel.Kitaplar</class>
<class>com.mesutemre.businesModel.Uyeler</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.logging.level" value="FINEST" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3307/kutuphane" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
</properties>
</persistence-unit>
Stacktrace;
WARNING: EJB5184:A system exception occurred during an invocation on EJB UyelerDAO, method: public com.mesutemre.businesModel.Uyeler com.mesutemre.businesDAOs.UyelerDAO.findMemberByUserName(java.lang.String)
WARNING: javax.ejb.TransactionRolledbackLocalException: Exception thrown from bean at com.sun.ejb.containers.BaseContainer.checkExceptionClientTx(BaseContainer.java:5071) at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4906) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222) at
SEVERE: Caused by: javax.ejb.TransactionRolledbackLocalException: Exception thrown from bean
SEVERE: at com.sun.ejb.containers.BaseContainer.checkExceptionClientTx(BaseContainer.java:5071)
SEVERE: at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4906)
SEVERE: at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
SEVERE: ... 71 more
SEVERE: Caused by: java.lang.IllegalArgumentException: Unknown entity bean class: class com.mesutemre.businesModel.Uyeler, please verify that this class has been marked with the #Entity annotation.
SEVERE: at org.eclipse.persistence.internal.jpa.EntityManagerImpl.find(EntityManagerImpl.java:648)
SEVERE:
It looks like this is a redeployment/caching problem with GlassFish. If you use transaction type RESOURCE_LOCAL and create the EntityManager manually and redeploy, it may be the case that the old EntityManager or the according factory is still cached by GlassFish and therefore only knows some old values.
The fastest solution should be a restart of GlassFish and redeployment of the application.
Another solution is closing the EntityManagerFactory explicitly on un/redeployment.
Anyway the preferred solution is to use transaction type JTA so the EntityManager gets managed by the container. This is a lot easier to use and less error-prone. Here is a short example:
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class FileDAO {
#PersistenceContext
private EntityManager em;
public void store(File file) {
em.persist(file);
}
}
See also:
Persistence-unit as RESOURCE_LOCAL or JTA?
persistence.xml different transaction-type attributes
JPA - Unknown entity bean class
Unknown entity class error message even though the entity is marked with #Entity annotation
Unknown entity bean class after hot deploy: netbeans 6.9 + glassfish 2.1 + eclipselink jpa 2.0
my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="caronteemirJPAprj">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>ERCOLE</non-jta-data-source>
<class>model.Customer</class>
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.OracleDialect"/>
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#172.31.62.61:1521:ERCOLE"/>
<property name="javax.persistence.jdbc.user" value="ELI"/>
<property name="javax.persistence.jdbc.password" value="eli"/>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
</properties>
</persistence-unit>
</persistence>
#Stateless
public class QueryBean implements Serializable {
/*
*
*/
private static final long serialVersionUID = -7101661704004061600L;
EntityManagerFactory emf = Persistence.createEntityManagerFactory("caronteemirJPAprj");
#PersistenceContext(unitName="caronteemirJPAprj")
private EntityManager em;
public QueryBean(){
em = emf.createEntityManager();
}
public List<Customer> findAll() {
Query query = em.createQuery("Select h from Customer h");
return (List<Customer>) query.getResultList();
}
public static void main(String[] args) {
QueryBean q = new QueryBean();
q.findAll();
}
}
I needed hibernate-entitymanager-4.1.4.Final
Using Play! Framework 2.0.2, when I add several items from my java project to my H2 test database I only see one single item in the ITEM table. The single item being the last entry that i've persisted. I thought that this my be due the db being recreated at every commit. I therefor thought of adding the JPA.ddl=update property in my application.conf file. But this simply breaks with the following error. What
Here is my code (in the Item.save() method):
package models;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Persistence;
#Entity
public class Item {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int id;
public String name;
public String dev;
public String type;
public int quantity;
public BigDecimal unitPrice;
public Item() {}
public Item(String name, String dev, String type, int quantity,
BigDecimal unitPrice) {
super();
this.name = name;
this.dev = dev;
this.type = type;
this.quantity = quantity;
this.unitPrice = unitPrice;
}
/**
* Insert this new computer.
*/
public void save() {
//this.id = id;
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPersistenceUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(this);
entityManager.getTransaction().commit();
entityManager.close();
}
}
Here is the error message
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named update
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:69) ~[hibernate-jpa-2.0-api-1.0.1.Final.jar:1.0.1.
Final]
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47) ~[hibernate-jpa-2.0-api-1.0.1.Final.jar:1.0.1.
Final]
at play.db.jpa.JPAPlugin.onStart(JPAPlugin.java:35) ~[play_2.9.1.jar:2.0.2]
at play.api.Play$$anonfun$start$1.apply(Play.scala:60) ~[play_2.9.1.jar:2.0.2]
at play.api.Play$$anonfun$start$1.apply(Play.scala:60) ~[play_2.9.1.jar:2.0.2]
at scala.collection.LinearSeqOptimized$class.foreach(LinearSeqOptimized.scala:59) ~[scala-library.jar:0.11.3]
I believe you're going to need a persistence.xml file to be contained within your /conf/META-INF/ directory, and from there need to define a persistence unit. I believe this is because you're using Hibernate correct?
An example of what yours can look like
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="update">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.url" value="jdbc:h2:mem:events"/>
</properties>
</persistence-unit>
</persistence>
In your tag you'll also need to include any <jar-file> or <class> you are to be using as well.