QueryProjection with List as one of the parameters - java

I'm writing a query for the following domain model
#QueryEntity
public class Person
{
...
private String name;
private List<String> addresses;
...
}
And I wish to have the query result return to me a representation of a person as there are too much other fields that I do no care about.
public class PersonRepresentation
{
private string name;
private List<String> addresses;
#QueryProjection
public PersonRepresentation(String name, List<String> addresses){
this.name = name;
this.addresses = addresses;
}
...
}
When I attempt to create my JPA query as such
private final QPersonRepresentation qPersonRepresentationProjection = new QPersonRepresentation(
qPerson.name,
qPerson.addresses
);
List<PersonRepresentation> result = new JPAQuery(em)
.from(qPerson)
.list(qPersonRepresentationProjection);
I get the following error:
java.lang.IllegalArgumentException: org.hibernate.QueryException: not
an entity [select person.name,
person.addresses from
com.example.foo.Person person]
at
org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1750)
at
org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
at
org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
at
org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:331)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
....
I've scurred both the documentation and the tests on the github and so far cannot come up with a reason why I cannot execute this query.

Related

Morphia Mapping Exemption : No usable constructor for org.springframework.security.access.intercept.AbstractSecurityInterceptor

I am using Morphia to map pojos for persistence operations with MongoDB. While the connection too the database is fine, I have the errors as shown in the stacktrace:
Exception in thread "main" org.mongodb.morphia.mapping.MappingException: No usable constructor for org.springframework.security.access.intercept.AbstractSecurityInterceptor
at org.mongodb.morphia.mapping.DefaultCreator.createInstance(DefaultCreator.java:81)
at org.mongodb.morphia.mapping.DefaultCreator.createInstance(DefaultCreator.java:91)
at org.mongodb.morphia.mapping.Mapper.fromDBObject(Mapper.java:192)
at org.mongodb.morphia.query.MorphiaIterator.convertItem(MorphiaIterator.java:134)
at org.mongodb.morphia.query.MorphiaIterator.processItem(MorphiaIterator.java:146)
at org.mongodb.morphia.query.MorphiaIterator.next(MorphiaIterator.java:117)
at org.mongodb.morphia.query.QueryImpl.asList(QueryImpl.java:147)
at org.mongodb.morphia.query.QueryImpl.asList(QueryImpl.java:139)
at de.hpi.ProcessorMongo.main(ProcessorMongo.java:52)
Caused by: java.lang.InstantiationException
at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.mongodb.morphia.mapping.DefaultCreator.createInstance(DefaultCreator.java:72)
... 8 more
Here is the POJO :
public class AuditLog {
#Id
private ObjectId logId;
#JsonProperty("#timestamp")
private String timestamp;
#JsonProperty("deviceId")
private String deviceId;
#JsonProperty("userId")
private String userId;
#JsonProperty("requestId")
private String requestId;
#JsonProperty("operationType")
private String operationType;
#JsonProperty("message")
private String message;
#JsonProperty("serviceName")
private String serviceName;
#JsonProperty("className")
private String className;
The query code:
MongoClient mongoClient = new MongoClient( "x.x.x.x" , 27017 );
Morphia morphia = new Morphia();
morphia.mapPackage("a.b.c");
final Datastore datastore = morphia.createDatastore(mongoClient, "myDB");
datastore.getDB(); //.collectionExists("mycollection");
datastore.ensureIndexes();
Query<AuditLog> query = datastore.find(AuditLog.class);
final List<AuditLog> auditLog = query.asList();
for (AuditLog logs : auditLog) {
System.out.println(logs.getClassName() + " " + logs.getDeviceId());
}
I will appreciate any pointers to what might be the issue or how to directly resolve these concerns.

Java JPA Illegal Argument Exception - NamedQuery of name: xyz not found

I am trying to get a user based on their ID using this named query, however I keep getting an illegal argument exception. I've been looking at this code for awhile. Hopefully someone may catch something I might've missed.
This is my ORM
#Entity
#Table(name = "MYUSER")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Myuser.findAll", query = "SELECT m FROM Myuser m"),
#NamedQuery(name = "Myuser.findByUserid", query = "SELECT m FROM Myuser m WHERE m.userid = :userid"),
#NamedQuery(name = "Myuser.findByName", query = "SELECT m FROM Myuser m WHERE m.name = :name"),
#NamedQuery(name = "Myuser.findByPassword", query = "SELECT m FROM Myuser m WHERE m.password = :password"),
#NamedQuery(name = "Myuser.findByEmail", query = "SELECT m FROM Myuser m WHERE m.email = :email"),
#NamedQuery(name = "Myuser.findByTel", query = "SELECT m FROM Myuser m WHERE m.tel = :tel"),
#NamedQuery(name = "Myuser.findByAddress", query = "SELECT m FROM Myuser m WHERE m.address = :address"),
#NamedQuery(name = "Myuser.findBySecqn", query = "SELECT m FROM Myuser m WHERE m.secqn = :secqn"),
#NamedQuery(name = "Myuser.findBySecans", query = "SELECT m FROM Myuser m WHERE m.secans = :secans")})
public class Myuser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "USERID")
private Integer userid;
#Column(name = "NAME")
private String name;
#Column(name = "PASSWORD")
private String password;
#Column(name = "EMAIL")
private String email;
#Column(name = "TEL")
private Integer tel;
#Column(name = "ADDRESS")
private String address;
#Column(name = "SECQN")
private String secqn;
#Column(name = "SECANS")
private String secans;
public Myuser() {
}
public Myuser(Integer userid) {
this.userid = userid;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getTel() {
return tel;
}
public void setTel(Integer tel) {
this.tel = tel;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSecqn() {
return secqn;
}
public void setSecqn(String secqn) {
this.secqn = secqn;
}
public String getSecans() {
return secans;
}
public void setSecans(String secans) {
this.secans = secans;
}
#Override
public int hashCode() {
int hash = 0;
hash += (userid != null ? userid.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 Myuser)) {
return false;
}
Myuser other = (Myuser) object;
if ((this.userid == null && other.userid != null) || (this.userid != null && !this.userid.equals(other.userid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "ejbentity.Myuser[ userid=" + userid + " ]";
}
}
This is my user facade
#Stateless
public class MyuserFacade implements MyuserFacadeRemote {
#PersistenceContext(unitName = "EJBServer-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public MyuserFacade() {
//super(Myuser.class);
}
#Override
public Myuser getUser(int userID) {
Myuser aUser = new Myuser();
aUser = (Myuser)em.createNamedQuery("Myuser.findByUserid").setParameter("userid", userID).getResultList();
return aUser;
}
}
My 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="EJBEntityPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!--<exclude-unlisted-classes>false</exclude-unlisted-classes>-->
<class>ejbentity.Myuser</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/EA"/>
<property name="javax.persistence.jdbc.password" value="test"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.user" value="test"/>
</properties>
</persistence-unit>
</persistence>
Error Log is given below:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.appclient.client.acc.AppClientContainer.launch(AppClientContainer.java:446)
at org.glassfish.appclient.client.AppClientFacade.main(AppClientFacade.java:166)
Caused by: javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:752)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:702)
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.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy266.getUser(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.IllegalArgumentException: NamedQuery of name: Myuser.findByUserid not found.
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:355)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:1135)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:522)
at stateless.MyuserFacade.getUser(MyuserFacade.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:73)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:205)
... 19 more
Java Result: 1
Actual error:
Caused by: java.lang.IllegalArgumentException: NamedQuery of name: Myuser.findByUserid not found.
Happens from:
#NamedQuery(name = "Myuser.findByUserid", query = "SELECT m FROM Myuser m WHERE m.userid = :userid"),
UPDATE:
From your persistence.xml:
<persistence-unit name="EJBEntityPU" transaction-type="RESOURCE_LOCAL">
Here you are using transaction-type="RESOURCE_LOCAL". So if you use it, then you are responsible for EntityManager.
Then you must have to follow (JPA Concepts: JPA 101)
You must use the EntityManagerFactory to get an EntityManager
The resulting EntityManager instance is a PersistenceContext/Cache
An EntityManagerFactory can be injected via the #PersistenceUnit
annotation only (not #PersistenceContext)
You are not allowed to use #PersistenceContext to refer to a unit of
type RESOURCE_LOCAL
You must use the EntityTransaction API to begin/commit around every
call to your EntityManger
Calling entityManagerFactory.createEntityManager() twice results in
two separate EntityManager instances and therefor two separate
PersistenceContexts/Caches.
It is almost never a good idea to have more than one instance of an
EntityManager in use (don't create a second one unless you've
destroyed the first)
Solution:
This is an example. you can follow the tutorial if you want to use RESOURCE_LOCAL.
Related Link:
DON'T USE JPA'S RESOURCE_LOCAL ON THE SERVER
Persistence unit as RESOURCE_LOCAL or JTA?
persistence.xml different transaction-type attributes
We got the same error and it was because the entities were missing in persistence.xml
In your persistence.xml is:
<persistence-unit name="EJBEntityPU"
but in your MyuserFacade you use:
#PersistenceContext(unitName = "EJBServer-ejbPU")
You should change that to:
#PersistenceContext(unitName = "EJBEntityPU")
I notice you have class ejbentity.Myuser in your persistence.xml. The class actually lives in a package structure consisting of one directory called "ejbentity"? The stacktrace suggests that your Myuser class with the NamedQuery annotations is not being found, which would be explained if your package structure is not being loaded as you expect.
I don't think that transaction-type has anything to do with #NamedQuery annotation.
This error
Caused by: java.lang.IllegalArgumentException: NamedQuery of name: Myuser.findAll not found.
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:355)
looks like an EclipseLink bug. Which version are you using ?

Embedded Sqlite database with Ormlite and JavaFX: error creating table

I am trying to persist some data in my JavaFX application.
My code fails when attempting to create a table in my PersistenceManager class:
private final static String DATABASE_URL = "jdbc:sqlite:my.db";
private final static String DATABASE_DRIVER = "org.sqlite.JDBC";
// ...
Class.forName(DATABASE_DRIVER);
DriverManager.getConnection(DATABASE_URL);
connectionSource = new JdbcConnectionSource(DATABASE_URL);
// here it fails:
TableUtils.createTable(connectionSource,MyClass.class);
A file my.db is actually created, but it is empty. When executing TableUtils.createTable, it triggers the following:
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
... 43 more
Caused by: java.lang.AbstractMethodError: com.j256.ormlite.jdbc.JdbcDatabaseConnection.compileStatement(Ljava/lang/String;Lcom/j256/ormlite/stmt/StatementBuilder$StatementType;[Lcom/j256/ormlite/field/FieldType;I)Lcom/j256/ormlite/support/CompiledStatement;
at com.j256.ormlite.table.TableUtils.doStatements(TableUtils.java:458)
at com.j256.ormlite.table.TableUtils.doCreateTable(TableUtils.java:441)
at com.j256.ormlite.table.TableUtils.createTable(TableUtils.java:221)
at com.j256.ormlite.table.TableUtils.createTable(TableUtils.java:54)
at org.lh.mypackage.mysubpackage.PersistenceManager.<init>(PersistenceManager.java:32)
My Class is this:
#DatabaseTable(tableName = "myclass")
public class MyClass {
#DatabaseField(id = true)
private String nome;
#ForeignCollectionField(eager = false)
private Collection<MyOtherClass> risposte;
protected MyClass() {
super();
}
}
and MyOtherClass is:
#DatabaseTable(tableName = "myotherclass")
public class MyOtherClass {
#DatabaseField(id = true)
private String nome;
#DatabaseField(foreign = true)
private MyClass scheda;
protected MyOtherClass() {
super();
}
}
I am using ormlite-core-4.49-SNAPSHOT.jar.
What should I look for correcting this?
For me solution has been to switch to ormlite-core-4.48. Same version for ormlite-jdbc driver. Now it works correctly.

Abstract Entity Persister Method get Property Values Illegal Argument Exception in Class

I'm getting error on DAO class Object[] property value variable,method of getPropertyValues(Object object ,EntityMode.Pojo); Is it correct way I am accessing property values based on property names ?please let me know where I have made mistaken ?
Using hibertnate-core 3.6.1 Final.jar.
My full Stack Trace :
[ERROR] IllegalArgumentException in class: com.zpmc.ecs.domain.ExportReport, getter method of property: description - (BasicPropertyAccessor.java:194)
org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of com.zpmc.ecs.domain.ExportReport.description
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:198)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValues(AbstractEntityTuplizer.java:482)
at org.hibernate.tuple.entity.PojoEntityTuplizer.getPropertyValues(PojoEntityTuplizer.java:241)
at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValues(AbstractEntityPersister.java:3857)
at com.zpmc.ecs.autoexportbean.AutoExportListenerService.getAllTables(AutoExportListenerService.java:327)
at com.zpmc.ecs.autoexportbean.AutoExportListenerService.buildReport(AutoExportListenerService.java:154)
at com.zpmc.ecs.autoexportbean.AutoExportListenerService.getAutoExportExcel(AutoExportListenerService.java:130)
at com.zpmc.ecs.autoexportbean.MyTask.run(AutoExportListenerBean.java:137)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:172)
... 9 more
Pojo Class :
#Entity
#Table(name ="T_KPI_AUTO_EXPORT_CONFIG")
public class ExportReport implements Serializable {
private String description;
#Column(name ="Description", nullable = false)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
DAO Class Method :
public List <String> getAllTables() throws SQLException {
Map<String, ClassMetadata> classMetaDataMap = hibernateTemplate.getSessionFactory().getAllClassMetadata();
for(Map.Entry<String, ClassMetadata> metaDataMap : classMetaDataMap.entrySet()) {
ClassMetadata classMetadata = metaDataMap.getValue();
AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) classMetadata;
tableName = abstractEntityPersister.getTableName();
String[] propertyNames = abstractEntityPersister.getPropertyNames();
for(int i=0;i<propertyNames.length;i++){
Object[] propertyvalue =abstractEntityPersister.getPropertyValues(ExportReport.class,EntityMode.POJO);
System.out.println(propertyType+"Columns: " + propertyNames+"ddddd"+propertyvalue);
System.out.println(propertyNames[i]);
System.out.println(propertyvalue[i]);
}
}
}

iam getting Caused by: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to retail.model.vo.Book

I am getting the exception below when type casting the list to a particular object. I think I'm doing it correctly. Can anyone suggest what is the wrong with the code?
SEVERE: Caused by: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to retail.model.vo.Book
SEVERE: at retail.ejb.service.ProductsSessionBeanImpl.showBookDetails(ProductsSessionBeanImpl.java:40)
SEVERE: at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
SEVERE: at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
SEVERE: at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
SEVERE: at java.lang.reflect.Method.invoke(Method.java:601)
SEVERE: at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
SEVERE: at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
SEVERE: at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
SEVERE: at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
SEVERE: at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
SEVERE: at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
SEVERE: at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
SEVERE: at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
SEVERE: at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
SEVERE: at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
SEVERE: at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
SEVERE: at java.lang.reflect.Method.invoke(Method.java:601)
SEVERE: at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
SEVERE: at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
SEVERE: at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
SEVERE: at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5360)
SEVERE: at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5348)
SEVERE: at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:206)
SEVERE: ... 54 more
#Override
public List<Book> showBookDetails() {
List<Book> book = em.createQuery("select p,b from Products p,Book b where p.productId=b.productId").getResultList();
//PRODUCT,book where PRODUCT.PRODUCT_ID = book.product_id
System.out.println("List Size:::"+ book.size());
//Customer obj = new Customer();
List<Book> booksList = new ArrayList<Book>();
for(int i=0; i<book.size();i++){
Book books = (Book) book.get(i);
System.out.println("Author ::::" + books.getAuthor() + "::ISBN ::"+books.getIsbnNumber()+"::pages::"+books.getNoOfpages()+"::price::"+books.getPrice()+
":::description::"+books.getProductDesc() + "::product id ::"+books.getProductId()+"::title::"+books.getProductTitle()+"::Stock::"+books.getStock());
booksList.add(books);
//obj.setCustomerList(customersList);
}
return booksList;
}
}
package retail.model.vo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
#Entity
#PrimaryKeyJoinColumn(name="product_id")
public class Book extends Products implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4264546498700495061L;
private String author;
private String isbnNumber;
private int noOfpages;
private String illustrations;
#Column(name = "author")
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
#Column(name = "isbn_number")
public String getIsbnNumber() {
return isbnNumber;
}
public void setIsbnNumber(String isbnNumber) {
this.isbnNumber = isbnNumber;
}
#Column(name = "noof_pages")
public int getNoOfpages() {
return noOfpages;
}
public void setNoOfpages(int noOfpages) {
this.noOfpages = noOfpages;
}
#Column(name = "illustrations")
public String getIllustrations() {
return illustrations;
}
public void setIllustrations(String illustrations) {
this.illustrations = illustrations;
}
}
em.createQuery("select p,b from Products p,Book b where p.productId=b.productId").getResultList();
actually returns a List of object arrays (List<Object[]>). The first element of the object array is a Product, and the second is a Book.
The compiler only complains with a warning in these cases because it doesn't know which generic type is returned from getResultList a priori. At runtime you don't get your ClassCastException at that line because of type erasure. The first actual cast of the Object[] in the List to the Book is done on the first list.get.
I guess the solution to your problem will be to change the query to:
List<Book> book = em.createQuery("select b from Products p,
Book b where p.productId=b.productId").getResultList();
Which actually will return a valid List of Books.
createQuery return list of objects here
change
List<Book> book = em.createQuery("select p,b from Products p,
Book b where p.productId=b.productId").getResultList();
to
List<Object[]> book = em.createQuery("select p,b from Products p,
Book b where p.productId=b.productId").getResultList();
If your query is returning a list of Object arrays, the simply change this line:
List<Object> book = em.createQuery("select p,b from Products p,Book b where p.productId=b.productId").getResultList();
And as you making a cast in the loop it will be fine:
Book books = (Book) book.get(i);
Just for information,
I got same problem with Neo4j objects transform using Spring to java entity
I had named query:
MATCH [bla-bla] RETURN a.name, a.associatedApplications
and the entity:
#QueryResult
#XmlRootElement
public class SomeDescriptor {
#ResultColumn("a.name")
private String name ;
#ResultColumn("a.associatedApplications")
private List<String> associatedApplications = new ArrayList<String>();
}
Same error:
Neo4j java.lang.classcastexception: [ljava.lang.string; cannot be cast to java.lang.iterable
After I used Neo4j COLLECT() function, all was working fine!
Updated named query:
RETURN a.name, COLLECT(a.associatedApplications) as associatedApplications
and updated the entity:
#QueryResult
#XmlRootElement
public class SomeDescriptor {
#ResultColumn("a.name")
private String name ;
#ResultColumn("associatedApplications")
private List<String> associatedApplications = new ArrayList<String>();
}

Categories

Resources