Entity class cannot be cast to java.lang.Number - java

This issue is a continuation of this problem: Foreign key as a part of composite primary key and ManyToOne relationship in OpenJPA
OpenJPA is tring to cast my entity class (TableB) to type of its key (long). Why?
Persisting of TableB object without any elements in field rows works fine. The problem begins when 'm adding elements to rows.
TableA.class:
package org.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
#IdClass(TableA_PK.class)
public class TableA implements Serializable {
#Id
private int fId;
#Id
private String item;
#Id
private String release;
#Id
#ManyToOne
#JoinColumn(name = "b_id")
private TableB tableB;
#Column
private String field1;
#Column
private String field2;
public TableA() {
}
public int getfId() {
return fId;
}
public void setfId(int fId) {
this.fId = fId;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getRelease() {
return release;
}
public void setRelease(String release) {
this.release = release;
}
public TableB getTableB() {
return tableB;
}
public void setTableB(TableB tableB) {
this.tableB = tableB;
}
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
}
TableA_PK.class:
package org.model;
import java.io.Serializable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public class TableA_PK implements Serializable {
private int fId;
private String item;
private String release;
private long tableB;
public TableA_PK() {
}
public int getfId() {
return fId;
}
public void setfId(int fId) {
this.fId = fId;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getRelease() {
return release;
}
public void setRelease(String release) {
this.release = release;
}
public long getTableB() {
return tableB;
}
public void setTableB(long tableB) {
this.tableB = tableB;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
TableA_PK rhs = (TableA_PK) obj;
return new EqualsBuilder().append(fId, rhs.fId).append(item, rhs.item)
.append(release, rhs.release).append(tableB, rhs.tableB)
.isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(fId).append(item).append(release)
.append(tableB).toHashCode();
}
}
TableB.class:
package org.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
#Entity
public class TableB implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column
private String name;
#Column
private Date date;
#OneToMany(mappedBy = "tableB", cascade = CascadeType.PERSIST)
private List<TableA> rows;
public TableB() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<TableA> getRows() {
return rows;
}
public void setRows(List<TableA> rows) {
this.rows = rows;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
TableB rhs = (TableB) obj;
return new EqualsBuilder().append(id, rhs.id).append(name, rhs.name)
.append(date, rhs.date).isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(id).append(name).append(date)
.toHashCode();
}
}
JpaTest.class:
package org.model;
import java.util.ArrayList;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.Test;
public class JpaTest {
#Test
public void test() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("rd-jpa");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();//BEGIN TRANSACTION 1.
TableB tableb = new TableB();
tableb.setDate(new Date());
tableb.setName("tableb2");
em.persist(tableb); // fills tableb id
userTransaction.commit(); //COMMIT 1
userTransaction = em.getTransaction();
userTransaction.begin();//BEGIN TRANSACTION 2.
TableA tableA = new TableA();
tableA.setfId(665);
tableA.setField1("field1");
tableA.setField2("field2");
tableA.setItem("item2");
tableA.setRelease("1");
tableA.setTableB(tableb);
ArrayList<TableA> rows = new ArrayList<TableA>();
rows.add(tableA);
tableb.setRows(rows);
em.persist(tableb);
userTransaction.commit();
em.clear();
em.close();
}
}
Stack Trace after running JpaTest:
<openjpa-2.3.0-r422266:1540826 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: org.model.TableB cannot be cast to java.lang.Number
at org.apache.openjpa.kernel.BrokerImpl.persistAll(BrokerImpl.java:2526)
at org.apache.openjpa.kernel.SingleFieldManager.persist(SingleFieldManager.java:279)
at org.apache.openjpa.kernel.StateManagerImpl.cascadePersist(StateManagerImpl.java:3081)
at org.apache.openjpa.kernel.BrokerImpl.persistInternal(BrokerImpl.java:2648)
at org.apache.openjpa.kernel.BrokerImpl.persist(BrokerImpl.java:2604)
at org.apache.openjpa.kernel.BrokerImpl.persist(BrokerImpl.java:2587)
at org.apache.openjpa.kernel.BrokerImpl.persist(BrokerImpl.java:2491)
at org.apache.openjpa.kernel.DelegatingBroker.persist(DelegatingBroker.java:1077)
at org.apache.openjpa.persistence.EntityManagerImpl.persist(EntityManagerImpl.java:716)
at org.model.JpaTest.test(JpaTest.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassCastException: org.model.TableB cannot be cast to java.lang.Number
at org.apache.openjpa.util.ApplicationIds$PrimaryKeyFieldManager.fetchLongField(ApplicationIds.java:669)
at org.apache.openjpa.enhance.org$model$TableA$pcsubclass.pcCopyKeyFieldsToObjectId(Unknown Source)
at org.apache.openjpa.enhance.PCRegistry.copyKeyFieldsToObjectId(PCRegistry.java:169)
at org.apache.openjpa.util.ApplicationIds.fromPKValues(ApplicationIds.java:224)
at org.apache.openjpa.enhance.ReflectingPersistenceCapable.pcNewObjectIdInstance(ReflectingPersistenceCapable.java:277)
at org.apache.openjpa.util.ApplicationIds.create(ApplicationIds.java:427)
at org.apache.openjpa.kernel.BrokerImpl.persistInternal(BrokerImpl.java:2675)
at org.apache.openjpa.kernel.BrokerImpl.persistAll(BrokerImpl.java:2521)
... 32 more
persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="rd-jpa" transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>org.model.TableA</class>
<class>org.model.TableB</class>
<properties>
<property name="openjpa.ConnectionURL"
value="jdbc:postgresql://localhost:5432/mydb" />
<property name="openjpa.ConnectionDriverName" value="org.postgresql.Driver" />
<property name="openjpa.ConnectionUserName" value="postgres" />
<property name="openjpa.ConnectionPassword" value="postgres" />
<property name="openjpa.DynamicEnhancementAgent" value="true" />
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
</properties>
</persistence-unit>
</persistence>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>jpa</groupId>
<artifactId>jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source />
<target />
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1102-jdbc41</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
</project>

Try to get rid of the openjpa.RuntimeUnenhancedClasses property and enhance your Entities properly.

Related

how to update, delete an object from Sql database using Hibernate?

Description
i simply want to implement ORM using Hibernate with mysql but the only
methods that are working are adding a single object to the database, returning
a list of objects, returning a list of objects by a keyword but deleting an
object and updating an object are not functioning!
any suggestion?
the table is created in the database with no problem :)
Entity
package dao;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Produit implements Serializable{
private static final long serialVersionUID = 8314029847799979249L;
#Id
private int ref;
private String desig;
private double prix;
private int quant;
public Produit() {}
public int getId() {
return ref;
}
public void setId(int ref) {
this.ref = ref;
}
public String getDesig() {
return desig;
}
public void setDesig(String desig) {
this.desig = desig;
}
public double getPrix() {
return prix;
}
public void setPrix(double prix) {
this.prix = prix;
}
public int getQuant() {
return quant;
}
public void setQuant(int quant) {
this.quant = quant;
}
}
Interface
package dao;
import java.util.List;
public interface InterfaceProduit {
public void addProduit(Produit produit);
public Produit getProduit(int id);
public List<Produit> getListProduit();
public List<Produit> getListProduitbykw(String mc);
public void updateProduit(Produit p);
public void deleteProduit(int id);
}
Iplementation
package dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.transaction.Transactional;
#Transactional
public class ImplInterfProduit implements InterfaceProduit{
EntityManager manager;
public ImplInterfProduit() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("sample");
manager = factory.createEntityManager();
}
public void addProduit(Produit produit) {
EntityTransaction transaction = manager.getTransaction();
transaction.begin();
try {
manager.persist(produit);
transaction.commit();
}catch(Exception ex) {
transaction.rollback();
ex.printStackTrace();
}
}
public Produit getProduit(int id) {
Produit p = manager.find(Produit.class, id);
return p;
}
public List<Produit> getListProduit() {
Query query = manager.createQuery("SELECT p FROM Produit p");
return query.getResultList();
}
public List<Produit> getListProduitbykw(String mc) {
Query query = manager.createQuery("SELECT p FROM Produit p where
p.desig LIKE :x");
query.setParameter("x", "%"+mc+"%");
return query.getResultList();
}
public void updateProduit(Produit p) {
manager.merge(p);
}
public void deleteProduit(int id) {
Produit p = manager.find(Produit.class, id);
manager.remove(p);
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="sample">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/product"/>
<property name="hibernate.connection.username" value="product"/>
<property name="hibernate.connection.password" value="product"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
</properties>
</persistence-unit>
</persistence>
Main
package dao;
public class MainApp {
public static void main(String[] args) {
Produit p = new Produit();
p.setId(9114);
p.setDesig("telecom");
p.setPrix(654.77);
p.setQuant(40);
ImplInterfProduit implProd = new ImplInterfProduit();
implProd.addProduit(p);
implProd.updateProduit(p);
implProd.deleteProduit(8760);
}
}
POM
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yusfi</groupId>
<artifactId>jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
</project>
Output
Hibernate: insert into Produit (desig, prix, quant, ref) values (?, ?, ?, ?)
Hibernate: select produit0_.ref as ref1_0_0_, produit0_.desig as desig2_0_0_,
produit0_.prix as prix3_0_0_, produit0_.quant as quant4_0_0_ from Produit
produit0_ where produit0_.ref=?
public List<Produit> getListProduit() {
Query query = manager.createQuery("FROM Produit", Produit.class);
return query.getResultList();
}
public List<Produit> getListProduitbykw(String mc) {
Query query = manager.createQuery("FROM Produit P WHERE P.desig LIKE :x", Produit.class);
query.setParameter("x", "%"+mc+"%");
return query.getResultList();
}

save value type collection in hibernate

How can I save collection of value type in hibernate with annotations - List of String List<String> or for example:
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
private Set<History> history;
}
and here is value type:
public class History {
private String someAttribute;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((entry == null) ? 0 : entry.hashCode());
result = prime * result + ((entryDate == null) ? 0 : entryDate.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
History other = (History) obj;
if (entry == null) {
if (other.entry != null)
return false;
} else if (!entry.equals(other.entry))
return false;
if (entryDate == null) {
if (other.entryDate != null)
return false;
} else if (!entryDate.equals(other.entryDate))
return false;
return true;
}
}
Can anyone give some example with hibernate annotations?
For an entity to have collection value type, we need to create a separate table to hold this collection as single row of the entity will have multiple values of for this collection. Use #ElementCollection and #CollectionTable annotations on the collection value attribute.
#ElementCollection
#CollectionTable(name = "STUDENT_HISTORY", joinColumns = {#JoinColumn(name = STUDENT_ID) })
#Column(name="HISTORY")
private Set<History> history;
The table will hold the collection values in the column HISTORY and uses STUDENT_ID column as the join column which will be the foreign key to the ID of student.
Below is a complete example using native Hibernate (I mean without the JPA):
Student.java
package domain.app.data;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
#Entity
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#ElementCollection
#CollectionTable(name="STUDENT_HISTORY", joinColumns={#JoinColumn(name="STUDENT_ID", referencedColumnName="ID")})
#Column(name="HISTORY")
private Set<History> history = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<History> getHistory() {
return history;
}
public void setHistory(Set<History> history) {
this.history = history;
}
#Override
public String toString() {
return "Student [id=" + id + ", history=" + history + "]";
}
}
History.java
package domain.app.data;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class History {
#Column(name="HISTORY")
private String someAttribute;
public String getSomeAttribute() {
return someAttribute;
}
public void setSomeAttribute(String someAttribute) {
this.someAttribute = someAttribute;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((someAttribute == null) ? 0 : someAttribute.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
History other = (History) obj;
if (someAttribute == null) {
if (other.someAttribute != null)
return false;
} else if (!someAttribute.equals(other.someAttribute))
return false;
return true;
}
}
HibernateUtil.java
package domain.app.data.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import domain.app.data.Student;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().build();
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Student.class);
return configuration.buildSessionFactory(serviceRegistry);
}
public static SessionFactory getSession() {
return sessionFactory;
}
}
Application.java
package domain.app;
import org.hibernate.Session;
import domain.app.data.History;
import domain.app.data.Student;
import domain.app.data.util.HibernateUtil;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSession().openSession();
session.getTransaction().begin();
Student student = new Student();
History history1 = new History();
history1.setSomeAttribute("Volunteer since 2016");
History history2 = new History();
history2.setSomeAttribute("Football team member");
student.getHistory().add(history1);
student.getHistory().add(history2);
session.save(student);
session.getTransaction().commit();
session.close();
}
}
hibernate.properties
hibernate.connection.username=admin
hibernate.connection.password=password
hibernate.connection.url=jdbc:h2:~/h2db/test
hibernate.connection.driver_class=org.h2.Driver
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<configuration debug="false" scan="true" scanPeriod="30 minutes">
<appender name="Console-Appender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%gray(%d{yyyy-MM-dd HH:mm:ss.SSS}) %highlight(%5p) %gray(---) %magenta([%15.15t]) %cyan(%-40.40c{1}) %black(:) %m%n%xEx</pattern>
</encoder>
</appender>
<root level="trace">
<appender-ref ref="Console-Appender" />
</root>
</configuration>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>stackoverflow</groupId>
<artifactId>SO-41248001</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.5.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
</dependencies>
</project>
Project Structure:
Result in DB:
try this it should work.
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#ElementCollection
private Collection Set<History> history;
}
#Embeddable
public class History {
private String someAttribute;
......
}

Cannot find the declaration of element 'persistence' JPA and hibernate provider

I am new in jpa and I am tryingg to write and execute a sample founded here:Sample JPA
This is my table created:
Here is my persistance.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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_0.xsd">
<persistence-unit name="EmployeeService" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>ir.ac.sbu.testsimplesql1.Employee</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/library?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="pass"/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="update"/>
</properties>
I have auto generate model class from database:
package ir.ac.sbu.testsimplesql1;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "Employee")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e"),
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE e.id = :id"),
#NamedQuery(name = "Employee.findByFistName", query = "SELECT e FROM Employee e WHERE e.fistName = :fistName"),
#NamedQuery(name = "Employee.findByLastName", query = "SELECT e FROM Employee e WHERE e.lastName = :lastName"),
#NamedQuery(name = "Employee.findByDept", query = "SELECT e FROM Employee e WHERE e.dept = :dept")})
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "fistName")
private String fistName;
#Column(name = "lastName")
private String lastName;
#Column(name = "dept")
private String dept;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFistName() {
return fistName;
}
public void setFistName(String fistName) {
this.fistName = fistName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "ir.ac.sbu.testsimplesql1.Employee[ id=" + id + " ]";
}
}
This is my poem.xml: (Dependencies Tag)
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.8.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.2</version>
</dependency>
</dependencies>
And the last thing is my main function:
public class EmployeeTest {
private static EntityManager em;
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeService");
em = emf.createEntityManager();
createEmployee(1, "Saint", "Peter", "Engineering");
createEmployee(2, "Jack", " Dorsey", "Imaginea");
createEmployee(3, "Sam", "Fox", "Imaginea");
}
private static void createEmployee(int id, String firstName, String lastName, String dept) {
em.getTransaction().begin();
Employee emp = new Employee();
emp.setId(id);
emp.setFistName(firstName);
emp.setLastName(lastName);
emp.setDept(dept);
em.persist(emp);
em.getTransaction().commit();
}
}
But when I run this code I face with this error:
I have searched this error bud couldn't understand what should I do. I've also visited this link:
Can not find the declaration of element 'persistence'
javax.persistence.PersistenceException - JPA+Hibernate
and alot more similar questions ....
Can anyone please help me to solve this error?
Thanks in advance for your attention.
You can check your XML against the XSD here : http://www.freeformatter.com/xml-validator-xsd.html
Very useful.
Replace the beginning of your xml with:
<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">
I don't know why, but yours is not validated.
Also, you miss the end of the xml, but i guess it's just a copy/paste error.

JPA OneToMany ManyToOne #OneToOne or #ManyToOne on references an unknown entity:

I am just not getting the point here. Whats going on with the following code, where is the error? I have to Classes: Ressource and Reservation. A Resource can have multiple Reserverations and the relation is bidirectional. To me, eveything seems find and I have looked at a bunch ressources and documentations - ah yep, also at a lot of examples and I cant get to the rootcause of this.
Any body of you gets the issue, or could somebody at least tell me that nothing is wrong with it:)
package org.ademi.model;
import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Entity;
#Entity
#Table(name="Ressource")
public class Ressource implements Serializable{
private static final long serialVersionUID = 12L;
/**
* A Ressource is available from a specific Date.
*/
private Calendar availableFrom;
/**
* A Ressource is available until specific Date.
*/
private Calendar availableTo;
/**
* This is a unique Ressource ID.
*/
private int id;
/**
* A set of reservations that belong to this ressource
*/
private List<Reservation> reservations;
/**
* A list of Days, when the ressource is available
*/
private List<Day> daysAvailable;
/**
* This is specifying the intervall aloud for the reservation;
*/
private Intervall intervall;
/**
* Type of the ressource
*/
private String type;
/**
* Name of the ressource
*/
private String name;
public Ressource(String name, String type, Calendar availableFrom, Calendar availableto, List<Day> daysAvailable, Intervall intervall){
this.availableFrom = availableFrom;
this.availableTo = availableto;
this.daysAvailable = daysAvailable;
}
#Temporal(TemporalType.DATE)
public Calendar getAvailableFrom() {
return availableFrom;
}
public void setAvailableFrom(Calendar availableFrom) {
this.availableFrom = availableFrom;
}
#Temporal(TemporalType.DATE)
public Calendar getAvailableTo() {
return availableTo;
}
public void setAvailableTo(Calendar availableTo) {
this.availableTo = availableTo;
}
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#OneToMany(mappedBy="Reservation",cascade = CascadeType.ALL)
public List<Reservation> getReservations() {
return reservations;
}
public void setReservations(List<Reservation> reservations) {
this.reservations = reservations;
}
#Enumerated(EnumType.STRING)
public Intervall getIntervall() {
return intervall;
}
public void setIntervall(Intervall intervall) {
this.intervall = intervall;
}
#ElementCollection(targetClass=Day.class)
#Enumerated(EnumType.STRING)
#CollectionTable(name="daysAvailable")
#Column(name="daysAvailable")
public List<Day> getDaysAvailable() {
return daysAvailable;
}
public void setDaysAvailable(List<Day> daysAvailable) {
this.daysAvailable = daysAvailable;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package org.ademi.model;
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="Reservation")
public class Reservation implements Serializable{
private static final long serialVersionUID = 1L;
/**
* A unique ID belonging to a reservation.
*/
private int id;
/**
* Timesstamp for the beginning of the reservation
*/
private Calendar reservationStarts;
/**
* Amount of Intervalls for the reservation
*/
private int reservedIntervalls;
/**
* A short summary Title describing the reservation
*/
private String title;
/**
* The resource which is reserved in this reservation.
*/
private Ressource ressource;
public Reservation(String title, Ressource ressource, Calendar reservationStarts, int reservedIntervalls){
this.title = title;
this.ressource = ressource;
this.reservationStarts = reservationStarts;
this.reservedIntervalls = reservedIntervalls;
}
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Temporal(TemporalType.TIMESTAMP)
public Calendar getReservationStarts() {
return reservationStarts;
}
public void setReservationStarts(Calendar reservationStarts) {
this.reservationStarts = reservationStarts;
}
public int getReservedIntervalls() {
return reservedIntervalls;
}
public void setReservedIntervalls(int reservedIntervalls) {
this.reservedIntervalls = reservedIntervalls;
}
#ManyToOne
#JoinColumn(name="ressource_ID")
public Ressource getRessource() {
return ressource;
}
public void setRessource(Ressource ressource) {
this.ressource = ressource;
}
}
My persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<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_1_0.xsd"
version="1.0">
<persistence-unit name="iplandb">
<properties>
<!--
<property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
-->
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="kbausbes"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/iplandb"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
</properties>
</persistence-unit>
</persistence>
A simple TestingClass
package org.ademi.client;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.ademi.model.Day;
import org.ademi.model.Intervall;
import org.ademi.model.Ressource;
public class TestClient {
public static void main(String[] args){
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("iplandb");
/* Create EntityManager */
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
ArrayList<Day> a = new ArrayList<Day>();
a.add(Day.FRIDAY);
Ressource r = new Ressource("ilir", "ademi", new GregorianCalendar(), new GregorianCalendar(),a, Intervall.EIGHT );
em.persist(r);
em.flush();
}
}
And this is the Exceptions I am getting:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: iplandb] Unable to configure EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:265)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:125)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:52)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34)
at org.ademi.client.TestClient.main(TestClient.java:20)
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on org.ademi.model.Reservation.ressource references an unknown entity: org.ademi.model.Ressource
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:81)
at org.hibernate.cfg.AnnotationConfiguration.processEndOfQueue(AnnotationConfiguration.java:456)
at org.hibernate.cfg.AnnotationConfiguration.processFkSecondPassInOrder(AnnotationConfiguration.java:438)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:309)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1162)
at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1226)
at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:173)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:854)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:191)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:253)
... 4 more
The class is annotated with #org.hibernate.annotations.Entity. It must be annotated with javax.persistence.Entity.
Fix your import.
Another problem is that mappedBy="Reservation" should be mappedBy="ressource". mappedBy contains the name of the property of the target class that is the owner side of the association.

Problems injecting EntityManager in GlassFish 4.1. ClassCastException (can't cast to same class)

I'm using:
GlassFish 4.1
Hibernate (see pom.xml)
Java EE 7
Eclipse Luna
I don't know why GlassFish can't inject an EntityManager. If i get the EntityManager from EntityManagerFactory, i don't have problems:
protected EntityManager em = Persistence.createEntityManagerFactory("CustomersPU").createEntityManager();
In other hand, if i try to say that GlassFish inject it, get an Exception.:
#PersistenceContext(unitName="CustomersPU")
protected EntityManager em;
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.localtest</groupId>
<artifactId>customersapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven_compiler_source>1.8</maven_compiler_source>
<maven_compiler_target>1.8</maven_compiler_target>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
GenericService
package me.localtest.customersapp.services;
import java.io.Serializable;
import java.util.List;
public interface GenericService<T, PK extends Serializable> {
public T save(T t) throws Throwable;
public T update(T t) throws Throwable;
public T remove(T t) throws Throwable;
public T find(PK pk) throws Throwable;
public List<T> findAll(String namedQuery) throws Throwable;
}
GenericServiceImpl
package me.localtest.customersapp.services;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
public abstract class GenericServiceImpl<T, PK extends Serializable> implements GenericService<T, PK> {
//#PersistenceContext(unitName="CustomersPU")
protected EntityManager em = Persistence.createEntityManagerFactory("CustomersPU").createEntityManager();
protected Class<T> clazz;
public GenericServiceImpl(Class<T> clazz) {
this.clazz = clazz;
}
#Override
public T save(T t) throws Throwable {
em.persist(t);
em.flush();
return t;
}
#Override
public T remove(T t) throws Throwable {
em.remove(t);
em.flush();
return t;
}
#Override
public T update(T t) throws Throwable {
em.merge(t);
em.flush();
return t;
}
#Override
public T find(PK pk) throws Throwable {
return (T) em.find(clazz, pk);
}
#SuppressWarnings("unchecked")
#Override
public List<T> findAll(String aQuery) throws Throwable {
Query query = em.createQuery(aQuery);
return (List<T>) query.getResultList();
}
}
CustomerServiceBean
package me.localtest.customersapp.services;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.Query;
import me.localtest.customersapp.domain.entities.Customer;
#LocalBean
#Stateless
public class CustomerServiceBean extends GenericServiceImpl<Customer, Integer> {
public CustomerServiceBean() {
super(Customer.class);
}
public Customer findByDni(String dni) {
Query query = em.createNamedQuery("Customer.findByDni");
query.setParameter("dni", dni);
return (Customer) query.getSingleResult();
}
}
Customer
package me.localtest.customersapp.domain.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name="customers")
#XmlRootElement(name="customer")
#XmlAccessorType(XmlAccessType.FIELD)
#NamedQueries({
#NamedQuery(name="Customer.findByDni", query="SELECT c FROM Customer c WHERE c.dni = :dni")
})
#SuppressWarnings("serial")
public class Customer implements Serializable {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
#XmlElement(name="id")
private Integer id;
#Column(name="names")
#XmlElement(name="names")
private String names;
#Column(name="surnames")
#XmlElement(name="surnames")
private String surnames;
#Column(name="dni")
#XmlElement(name="dni")
private String dni;
#Column(name="birth_date")
#XmlElement(name="birth-date")
#Temporal(TemporalType.DATE)
private Date birthDate;
#Column(name="address")
#XmlElement(name="address")
private String address;
#Column(name="email")
#XmlElement(name="email")
private String email;
#Column(name="creation_date")
#Temporal(TemporalType.DATE)
#XmlElement(name="creation-date")
private Date creationDate;
#Column(name="state")
#XmlElement(name="state")
private Boolean state;
public Customer() {
}
public Customer(Integer id, String names, String surnames, String dni,
Date birthDate, String address, String email, Date creationDate,
Boolean state) {
this.id = id;
this.names = names;
this.surnames = surnames;
this.dni = dni;
this.birthDate = birthDate;
this.address = address;
this.email = email;
this.creationDate = creationDate;
this.state = state;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
public String getSurnames() {
return surnames;
}
public void setSurnames(String surnames) {
this.surnames = surnames;
}
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Boolean getState() {
return state;
}
public void setState(Boolean state) {
this.state = state;
}
}
persistence.xml
<persistence-unit name="CustomersPU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/__customers</jta-data-source>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
</properties>
</persistence-unit>
Stage 1
Try to find Customer with DNI 'A' (RESTful):
http://localhost:8080/customersapp/api/customers/find/A
This is a piece stack trace:
2015-04-06T09:19:31.088-0500|Advertencia: A system exception occurred during an invocation on EJB CustomerServiceBean, method: public me.localtest.customersapp.domain.entities.Customer me.localtest.customersapp.services.CustomerServiceBean.findByDni(java.lang.String)
2015-04-06T09:19:31.089-0500|Advertencia: javax.ejb.TransactionRolledbackLocalException: Exception thrown from bean
at com.sun.ejb.containers.EJBContainerTransactionManager.checkExceptionClientTx(EJBContainerTransactionManager.java:662)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy267.findByDni(Unknown Source)
at me.localtest.customersapp.services.__EJB31_Generated__CustomerServiceBean__Intf____Bean__.findByDni(Unknown Source)
And this is the cause:
Caused by: java.lang.ClassCastException: me.localtest.customersapp.domain.entities.Customer cannot be cast to me.localtest.customersapp.domain.entities.Customer
I found this stupid, how is possible can't cast to the same class?
Thanks.
Appeared to be the result of classloder problems GF 4.x is having with the hibernate version 4.3.8.Final
Most probably it relates to HHH-9446 Also it looks like it was fixed 2 days ago. Have not yet had a chance to try it though
Well, i could not find solution for this problem. I switched to WildFly 8.2.0, and no problems. Anyway, i hope someday to know why this happens xD.
Thanks.

Categories