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
Related
When i try persist my Entity I get this exception:
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.EntityManagerSetupException
Runtime Exceptions:
Exception Description: Deployment of PersistenceUnit [h2] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.IntegrityException
Exception [EclipseLink-7198] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.ValidationException
Descriptor Exceptions:
Exception Description: Class: [uuid] was not found while converting from class names to classes.
Internal Exception: java.lang.ClassNotFoundException: uuid
Entity
#Entity
#UuidGenerator(name = "uuid")
#Converter(name = "uuidConverter", converterClass = UUIDConverter.class)
#Table(name = "ELECTRIC_METERS")
#NamedQuery(name = "ElectricMeters.findElectricMetersByNote",
query = "SELECT e FROM ElectricMeters e WHERE e.note = :note")
public class ElectricMeters implements Serializable{
#Id
#GeneratedValue(generator = "uuid", strategy = IDENTITY)
#Convert("uuidConverter")
#Column (name = "ID")
private UUID id;
#Column(name = "ADD_YARD_LIGHTING")
private boolean addYardLighting;
#Column(name = "NOTE")
private String note;
public ElectricMeters() {
}
//getters setters
}
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="h2" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- Converter -->
<class>com.art.forestbucha.util.UUIDConverter</class>
<class>com.art.forestbucha.entity.ElectricMeters</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:file://home/artem/NetBeansProjects/ForestBuchaBackEnd/src/main/resources/db/bucha"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
</properties>
</persistence-unit>
</persistence>
Converter
import java.util.UUID;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.DirectCollectionMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.sessions.Session;
public class UUIDConverter implements Converter{
#Override
public Object convertObjectValueToDataValue(Object objectValue,
Session session) {
return (UUID) objectValue;
}
#Override
public UUID convertDataValueToObjectValue(Object dataValue,
Session session) {
return (UUID) dataValue;
}
#Override
public boolean isMutable() {
return true;
}
#Override
public void initialize(DatabaseMapping mapping, Session session) {
final DatabaseField field;
if (mapping instanceof DirectCollectionMapping) {
// handle #ElementCollection...
field = ((DirectCollectionMapping) mapping).getDirectField();
} else {
field = mapping.getField();
}
field.setSqlType(java.sql.Types.OTHER);
field.setTypeName("uuid");
field.setColumnDefinition("UUID");
}
}
create database:
CREATE TABLE PUBLIC.ELECTRIC_METERS
(ID UUID NOT NULL PRIMARY KEY,
ADD_YARD_LIGHTING BOOLEAN DEFAULT false NOT NULL,
NOTE VARCHAR(255));
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 have error in Spring JPA when I call findAll method:
org.springframework.data.mapping.PropertyReferenceException: No property package found for type models.Apk
#Entity
#Table(name="Apks")
public class Apk implements Serializable {
#EmbeddedId private ApkPk id;
#Column private String fileName;
#Column private String description;
#Column(updatable=false)
#Temporal(TemporalType.TIMESTAMP)
private Date creationTime;
#Column
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdateTime;
#ManyToOne
#JoinColumn(name="appId", referencedColumnName="appId", insertable=false, updatable=false)
#NotFound(action=NotFoundAction.IGNORE)
#JsonIgnore
private App app;
//Getters and setters
}
package mypackage.repositories;
public interface ApkRepository extends PagingAndSortingRepository<Apk, ApkPk> {
public List<Apk> findByFileName(String value);
}
applicationContext.xml
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="myjpa" />
</bean>
I have many repository classes but only this one occurs error. I found that Spring Data checks the naming convention according to the entity class, so my repository name should be ApkRepository. But it is not the case.
What can I fix this problem?
Any help would be appreciated.
EDIT:
When I do unit test, it works fine. I happens error when it calls through service class.
repository.findAll(new PageRequest(1, 30));
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.
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.