casting an object array to a JPA entity array? - java

I am getting a casting exception every time I attempt to get an array of entities out of list of entities that I pull back from a jpa call. Example...
QuickLaunch[] qLaunchArr = null;
List<QuickLaunch> listQL = null;
try
{
System.out.println("testing 1..2..3");
//qLaunchArr
listQL = emf.createNamedQuery("getQuickLaunch").getResultList();
Object[] objArr = listQL.toArray();
//System.out.println(listQL.size());
qLaunchArr = (QuickLaunch[]) listQL.toArray();
}
catch (Exception e)
{
System.out.println("Bull Hockey!!!! I can't believe it's not butter!: "+e.toString());
}
[Ljava.lang.Object; incompatible with [Lcom.upmc.esdm.messaging.entities.QuickLaunch;
That was in my server logs... (I am using WID)
and I also get this exception...
commonj.connector.runtime.DataHandlerException: CWLAP0507E: The response bean class for java class method GetAllQuickLaunchComponents cannot be created. Reason java.lang.IllegalArgumentException: argument type mismatch.

You can try TypedQuery to get the list of entities without explicit casting & prevent exceptions.
TypedQuery<QuickLaunch> listQL = em.createNamedQuery("QuickLaunch.getQuickLaunch", QuickLaunch.class);
List<QuickLaunch> products = listQL .getResultList();
Also, changed query name to identify its class or result type in more meaningful way.

Alright... I think I found the answer. It was inspired by this post...
https://stackoverflow.com/a/8060077/729820
I basically do this
try
{
System.out.println("testing 1..2..3");
listQL = emf.createNamedQuery("getQuickLaunch").getResultList();
System.out.println("What is the size of this list: number "+listQL.size());
qLaunchArr = listQL.toArray(new QuickLaunch[listQL.size()]);
}
All exceptions seem to clear right up.
Thanks for the help guys.

This isn't to do with JPA but Java, as it will not cast Object[] to QuickLaunch[]. Can you not use the Object array instead of a QuickLaunch[] array?

Related

Convert list of objects to array. Getting ArrayStoreException

I do have such piece of code:
List<VersionedUserIdentifier> userIdentifiers = getUsersModule().getUsersIdentifiers();
if (userIdentifiers.isEmpty()) {
LOG.info(No users to verify.");
return;
}
VersionedUserIdentifier[] vIds = userIdentifiers.toArray(new VersionedUserIdentifier[0]);
I'm getting an error:
java.lang.ArrayStoreException
at java.util.ArrayList.toArray(ArrayList.java:133)
I cannot convert list to array. Any ideas what could be wrong?
I have also tried:
VersionedUserIdentifier[] vIds = userIdentifiers.toArray(new VersionedUserIdentifier[userIdentifiers.size()]);
This type of exception happens when you try to store different type of the object in the array.
Refer the below link
Oracle doc
This works for me..Please check
List<VersionedUserIdentifier> userIdentifiers = getUsersModule().getUsersIdentifiers();
VersionedUserIdentifier[] vui=(VersionedUserIdentifier[])userIdentifiers.toArray();
Stream.of(vui).forEach(System.out :: println);

Get Field value from entity using DTO

I have an app with several #MappedSuperClasses. Out of one of them I need to write a csv with columns in a very particular order stablished by the client.
Doing a Entity.class.getDeclaredFields() used to be enough to retrieve and write the columns in the right order before we had superclasses, but now, even if I use a custom solution to iterate through the superclasses's fields the order is incorrect, so I resorted to using a DTO Entity which returns the right order when calling getDeclaredFields().
The problems come when I try to retrieve the values present in the entities related, we used to do something like:
Object value = getLineFromField(field, line);
Where getLineFromField() method would be like:
private Object getLineFromField(Field field, Entity line) {
Object value = null;
try {
value = field.get(line);
} catch (Exception e) {
LOG.info("There is no value. Adding a WhiteSpace to the Column Value");
}
return value;
}
The problem appears in the field.get(line), this method from the Field library will always return a null value
Any experience out there doing a similar mapping?
Just trying to avoid writing a super-ugly 100-liner switch case in the codebase...
EDIT to add internal exception I get from the Field library: UnsafeObjectFieldAccessorImpl

Java : What is the best way to check variable type in runtime?

I want to know the best way to check variable type at runtime.
public Iterator<?> read(String entityName, String propertyName, Object propertyValue) {
String query = "select * from " + entityName + " where " + propertyName + "=";
try {
int value = Integer.parseInt((String)propertyValue);
query=query+value;
} catch (NumberFormatException e) {
// failed
}
try {
String value = (String)propertyValue;
query=query+"'"+value+"'";
} catch (ClassCastException e) {
// failed
}
try {
float value = Float.parseFloat((String)propertyValue);
query=query+value;
} catch (NumberFormatException e) {
// failed
}
//Creating JDBC connection and execute query
Iterator<Element> result=queryConn.execute();
return result;
}
I need to check the variable type is int, float or String during runtime. Is there any other best way to do this?
Or Do I need to write seperate method for each variable type?
try this code :
if(floatVariable instanceof Float){}
if(intVariable instanceof Integer){}
if(stringVariable instanceof String){}
There are many ways to handle this scenario.
Use function overloading for different data types
Use instanceof operator to determine data type
Try to cast property value in any numeric data type, if successfully castes then ignore single quotes otherwise apply single quotes
since you are getting object as input you can always check using instanceof keyword.And instead of using primitives try using classes like(Integer.class).And one more thing is you should use PreparedStatement always.Your code is prone to SqlInjection.
Is there any other best way to do this?
I would recommend that you name the columns you want to select in your actual query. If you take this approach, you can parse each column as the appropriate type without worrying about type casting issues. If, for example, the first column selected were an integer type, then you would just call Integer.parseInt() without worrying about having the wrong type.
And here is an argument why using SELECT * is an anti-pattern:
If you use SELECT * as your query, then we don't even know how many columns are being returned. To even take a guess at that, we would have to analyze how many columns your code seems to expect. But, what would happen if someone were to change the schema, thereby possibly changing the order in which the RDBMS returns columns? Then your entire application logic might have to change.

Exception occurred during event dispatching:java.lang.ClassCastException

I've been receiving ClassCastException in my code. Objective initially was to convert Set to List since the refreshDetailVOTable method will only get Set. The problem could have been in converting Set to List. refreshDetailVOTable might took the wrong List that's why I'm receiving ClassCastException. Any thoughts on this?
public List deleteChildPromotionComponentDetails(ClientContext context, List detailIRsToDelete,
String emergencyAccessPermission) throws RetekBusinessException {
List exclusionList = null;
RpmEvent deleteEvent = buildPromotionComponentDetailsDeleteEvent(emergencyAccessPermission);
deleteEvent.setTransitionNotificationExceptionFlag(true);
Set detailBOsToDelete = new HashSet();
for (Iterator iDetails = detailIRsToDelete.iterator(); iDetails.hasNext();) {
IdentifiableReference detailIR = (IdentifiableReference) iDetails.next();
PromotionComponentDetail promotionComponentDetail = (PromotionComponentDetail) getService()
.readForUpdate(detailIR);
Set exclusionSet = promotionComponentDetail.getExceptionsAndExclusions();
exclusionList = new ArrayList (exclusionSet);
for(Iterator exclusion = exclusionSet.iterator(); exclusion.hasNext();){
PromotionComponentDetail exclusionDel = (PromotionComponentDetail) exclusion.next();
exclusionDel.accept(deleteEvent);
detailBOsToDelete.add(promotionComponentDetail);
}
}
return exclusionList;
}
public void deleteChildDetails(final List parentComponentDetails)
{
List list = null;
try {
list = getCmlPromotionComponentDetailAppService().deleteChildPromotionComponentDetails(
ClientContext.getInstance(), parentComponentDetails,
emergencyPermission.getName());
} catch (RetekBusinessException e) {
e.printStackTrace();
}
refreshDetailVOTable(list);
}
Take a look at the generics tutorial here:
http://docs.oracle.com/javase/tutorial/java/generics/
You're doing pretty simple stuff, so you only need to look at the first part. You probably don't need to dive into wildcards.
A guess as to what's happening: your method is receiving a parameter List detailIRsToDelete from which you get an iterator and iterate over the elements like so:
for (Iterator iDetails = detailIRsToDelete.iterator(); iDetails.hasNext();) {
IdentifiableReference detailIR = (IdentifiableReference) iDetails.next();
...
}
If whoever calls you had accidentally put something other than an IdentifiableReference into detailIRsToDelete, you'd get a ClassCastException in the assignment statement within the loop. If instead the list parameter were declared
List<IdentifiableReference> detailIRsToDelete
the act of putting things into this list would be checked by the compiler, and the error would occur at the point where the erroneous object was added, at compile time, instead of later at runtime, as you're experiencing.

class cast exception in google app engine code

I am trying to query the data store and cast it to a user defined object type. But, i am getting an class cast error. Please look into the code
import com.gwt.samples.shared.List;
public ArrayList<String> viewLists(String user_id) {
PersistenceManager pm = PMF.get().getPersistenceManager();
ArrayList<String> res;
String[] ret;
Query q=pm.newQuery(List.class);
q.setFilter("owner_id == useridparam");
q.declareParameters("String useridparam");
try
{
res=(ArrayList<List>)q.execute(user_id); //error occurs here i guess
}
finally
{
q.closeAll();
}
return res;
}
The problem occurs because query.execute returns an Object and it cannot be casted to the type ArrayList . But, i am following this example from here
Please help
May I suggest:
1.Delete the line
import com.gwt.samples.shared.List;
2.Instead of
Query q=pm.newQuery(List.class);
and
res=(ArrayList<List>)q.execute(user_id); //error occurs here i guess
use
Query q=pm.newQuery(com.gwt.samples.shared.List.class);
and
res=(ArrayList<java.util.List>)q.execute(user_id);
When you say "error occurs here i guess", I presume that you can find out definitely by examining the relevant exception stack trace or log entry.
Also, I have just seen that your data member res is of data type ArrayList<String>, whereas your query will return (incorporating my code changes above) java.util.List<com.gwt.samples.shared.List>.
You will need to change the data type of either your query or res to get things to work.
I have a standard method for querying. The query return is stored in a java.util.List. I then do
java.util.List liResult = [My query];
ArrayList alResult = new ArrayList(liResult);
Ouside of my method, I cast my ArrayList to ArrayList<[Query data type]>.
Any help?

Categories