i got an error after submit my set to database like this
java.lang.String cannot be cast to java.lang.Integer
And, i dont have no idea about to parse this List to integer
carFamilySelectList = new ArrayList<SelectItem>();
List<CarFamily> carFamilyList = carFamilyServiceImpl.selectCarFamilyIdList();
carFamilySelectList.add(new SelectItem("", "Select one"));
for(CarFamily as : carFamilyList) {
carFamilySelectList.add(new SelectItem(as.getCarFamilyId(), as.getCarFamilyName()));
}
Please help!
It's hard to say for sure without what line of code in the database(?) is throwing the exception but my guess is that the cause is that first list entry that's causing the problem:
carFamilySelectList.add(new SelectItem("", "Select one"));
I'm assuming that CarFamily.getCarFamilyId() returns an int, and that the return value of SelectItem.getValue() is being cast to an Integer somewhere? That first list entry is a SelectItem with an empty string as its value. Try using 0 (or -1 or whatever) instead:
carFamilySelectList.add(new SelectItem(0, "Select one"));
But in the future, include more relevant information in your question (the line where the exception is thrown and at least the signatures for the methods in your custom class that are relevant to your question... like getCarFamilyId() in this case).
Related
I have a section of code that used to utilize Optional<Department>, but due to some errors I worked out I am now converting it to List<Department>. Obviously this means I now have to change the return types and other method calls. Here are my questions:
I changed my returns to "new LinkedList<>()" (indicated in the code below) but is that correct?
There is a red error under ".isPresent" (indicated in the code below) with error message "The method isPresent() is undefined for the type List<Department>". What should I be changing that to?
Below is the updated code with comments indicating where errors are now occurring. Any help and explanations would be GREATLY appreciated!
public List<Department> delete(String department_ID) {
if ((department_ID == null) || (department_ID.isEmpty())) {
return new LinkedList<>(); //<<<<<<<<<<<<<<< used to be "return Optional.empty();"
}
List<Department> existing = get(department_ID);
if (existing.isPresent()) { //<<<<<<<<<<< red error under ".isPresent()"
String sql = "DELETE employee.*, department.* " + "FROM employee, department "
+ "WHERE employee.department_ID = :department_ID AND department.department_ID = :department_ID;";
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("department_ID", department_ID);
int rows = jdbcTemplate.update(sql, parameters);
if (rows > 0) {
return existing;
}
}
return new LinkedList<>(); //<<<<<<<<<<<<<<< used to be "return Optional.empty();"
}
I changed my returns to "new LinkedList<>()" (indicated in the code below) but is that correct?
I have googled the error message for my ".isPresent" error and cant find any explanations that fit
tl;dr
Change:
if (existing.isPresent()) { …
… to:
if ( ! list.isEmpty() ) { …
Details
You said:
red error under ".isPresent" (indicated in the code below) with error message "The method isPresent() is undefined for the type List".
The variable existing holds a reference to a List object. If you look at the Javadoc for List, you find no method named isPresent. So of course trying to call a non-existent method generates an error from the compiler.
That isPresent method was from the Optional class. The method checks to see if the optional holds a payload or if the optional is empty.
You seem to be switching to a style where you always expect a List, even if the list is empty (no elements).
If you want to be defensive, you can check that the list object exists.
if ( Objects.nonNull( existing ) ) { … }
But you can omit that null check if you are confident that such a condition cannot exist.
You may want to check if the list is empty, to avoid a needless call to your database. If so, change that code to:
if ( ! list.isEmpty() ) // Perform database work only if list has some elements.
You have other issues. Among them:
Generally the convention in Java is to avoid underscores in names. And generally best to avoid ALL-CAPS. So departmentId, not department_ID.
When returning lists, generally best to return an unmodifiable list. If the calling programmer needs a modifiable list, they can easily make from the returned unmodifiable list.
To get an unmodifiable list, use List.of rather than new LinkedList<>().
I cannot understand why your delete method would return a list. You may believe that you are reporting rows that got deleted, but technically you are not.
By the way, a tip: Text blocks can help with embedded SQL.
Instead of returning new LinkedList<>() you could return List.emptyList().
isPresent() is a method of Optional, but you assign the outcome of method get(department_ID) to an instance of List. You can check the List using
if(!(existing == null || existing.isEmpty())) {
This question probably is easy. I am trying to read a field of a IBM Maximo application and use this value in the method getList(). The value I want to use was not saved in the database yet.
Here is some pseudocode:
#Override
public MboSetRemote getList() throws MXException, RemoteException {
MboSetRemote result = super.getList();
//Here is where i dont know how to do it
Date field = getFieldValue(FieldName)
//Here is where i want to use the value
String string = "....field..."
result.setWhere(string);
return result;
}
Thanks everyone,
Regards
I think the easiest and safest means to achieve your end of using the field value in your where clause is to use a bind variable, like this:
#Override
public MboSetRemote getList() throws MXException, RemoteException {
MboSetRemote result = super.getList();
//Here is where i want to use the value
String string = "....:fieldName...";
result.setWhere(string);
return result;
}
Notice the colon on the front of :fieldName in string. When Maximo sees this, it will look (not case-sensitive) on the current record / Mbo for an attribute named fieldName and replace :fieldName with the value in the attribute -- wrapped in quotes or whatever, as applicable to the attribute's type (ALN, UPPER, DATE, etc).
This approach is better than the approach you presented because it will employ Maximo's framework to prevent SQL injection attacks and etc.
That said, the way to get the field value would be as follows:
Date fieldValue = getMboValue("FieldName").getDate();
Further, I strongly suggest you get yourself a copy of Maximo's JavaDocs. You can do that here.
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?
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?
In our Java program we receive an Erlang tuple and extract it in OtpErlangTuple. One of the elements of the tuple should be a string but can be empty. When it is empty, its value is [] - the Erlang way of representing an empty list.
My question is how to check if the element is empty so to cast it to a OtpErlangString?
As it is now (OtpErlangString)messageData.elementAt(2), the following exception is raised:
class java.lang.ClassCastException
, 'com.ericsson.otp.erlang.OtpErlangList cannot be cast to com.ericsson.otp.erla
ng.OtpErlangString'
Thanks,
Martin
Check if it is equal to [] and do a specific operation if so:
OtpErlangString convertedString;
if(messageData.elementAt(2).toString().equals("[]")) {
// do something assigning some value to convertedString
} else {
convertedString = (OtpErlangString) messageData.elementAt(2);
}
You can handle this case the way you want depending on how you then manage those OtpErlangString