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?
Related
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).
I'm working on an application with spring-ibatis integration in which I have to log some of the query performed. So what I'd like to do, is basically getting the SQL from the ibatis mapped statements in the XML config file and then add somehow the parameters. I've been able to get the query with this lines of code:
MappedStatement ms = (MappedStatement) ((SqlMapClientImpl) sqlMapClient)
.getDelegate().getMappedStatement(queryId);
ms.setParameterClass(HashMap.class);
RequestScope scope = new RequestScope();
scope.setStatement(ms);
String sql = ((DynamicSql) ms.getSql()).getSql(scope, params);
So with the first row I get the MappedStatement and with the last one I get the raw query. The problem is that even if I'm passing to it the object with the query parameters, the SQL still has the parameters placeholders '?' (in the XML query they are named parameters, not positionals).
I have tried to set the parameterClass field instead of the parameterMap as suggested here but with no success. I'm not sure on how to work with the inline parameters.
I'm using ibatis-sqlmap 2.3.0 and spring-ibatis 2.0.8.
As you have probably noticed I have little to no knowledge of iBatis. Also, please I know that this is dirty and that I'm using classes that I'm not supposed to, no need to point that out.
Thank you for the help.
I've solved this problem and I want to share the solution for future readers that may have the same issue. Before doing that, keep in mind that this is NOT the way you should work with iBatis but only a dirty workaround to get the underlying SQL.
First of all, we need to group iBatis queries in at least 2 groups:
Static queries, they are simple mapped statements without any conditional elements.
Dynamic queries, they are mapped statements with conditional elements (e.g. isEqual, isGreaterThan, isNull...).
Once you have done this difference, here's the code to get the SQL:
public static String getSQLFromDynamicQuery(SqlMapClient sqlMapClient,
String queryId, Object paramObject) {
// Gets the SQL and parameters.
MappedStatement ms = ((SqlMapClientImpl) sqlMapClient).getDelegate()
.getMappedStatement(queryId);
RequestScope scope = new RequestScope();
scope.setStatement(ms);
String sql = ((DynamicSql) ms.getSql()).getSql(scope, paramObject);
Object[] params = ms.getSql().getParameterMap(scope, paramObject)
.getParameterObjectValues(scope, paramObject);
// Adds params to the query.
return bindQueryParam(sql, params);
}
public String getSQLFromStaticQuery(SqlMapClient sqlMapClient,
String queryId, Object... params) {
// Gets the SQL.
String sql = ((StaticSql) ((SqlMapClientImpl) sqlMapClient)
.getDelegate().getMappedStatement(queryId).getSql()).getSql(
null, null);
// Adds params to the query.
if (params != null) {
sql = bindQueryParam(sql, params);
}
return sql;
}
public static String bindQueryParam(String sql, Object... params) {
String result = sql;
for (Object param : params) {
result = result.replaceFirst("\\?",
param == null ? "null" : param.toString());
}
return result;
}
The bindQueryParam method replaces the question marks in the query with an array of object. For a static query, you will have to pass that array meanwhile for the dynamic one you can pass an Object or a java.util.Map, according to what is your parameterClass of the Mapped Statement.
Both methods use explicit subcasting (I've spent a lot of time looking at the source code to figure out how to make this work as you can imagine), so you may want to pay attention to call the right method according to the Mapped Statement you are processing or you will get a ClassCastException.
Again, this is not the recommended way but it works if you need it.
For an app I'm working on, I'm using Parse (www.parse.com) and I have two different pointer arrays in the _User class. That class contains two columns that I'm trying to include in my query: "following" and "friends".
My problem is that the result is always either null or empty pointers, depending on how I query it.
Parse mentions:
In some situations, you want to return multiple types of related objects in one query. You can do this with the include method.
However, using this include method causes the results to be null. This is my code:
ParseQuery<AAUser> query = ParseQuery.getQuery(AAUser.class);
query.include("following");
query.include("friends");
query.getInBackground(ParseUser.getCurrentUser().getObjectId, new GetCallback<AAUser>() {
#Override
public void done(AAUser user, ParseException e) {
if(e != null)
return;
Log.d(TAG, String.valueOf(user.getFollowing()));
}
});
user.getFollowing() alwas returns [null] whenever I include that field. However, if I don't include it, it returns an empty pointer as it should. [AALocation{id='iLUigvrvrc'}]
As you can see, I queried my subclassed AAUser class. I still get the same results by querying the ParseUser class so I don't see how subclassing made a difference.
How can I solve this issue? Is this a bug with the Parse SDK? I'm using version 1.7.1 of the Parse Android SDK.
.
I'm basically trying to refresh the current user data with these fields included but I see it's not working as it should...
And yes, I tried fetchInBackground() but it doesn't give me any ways to include those fields. My current workaround is to use the empty pointers and query all of them one by one but I find this to be an awful workaround... please halp.
Try this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.include("following");
query.include("friends");
query.findInBackground(new FindCallback<ParseObject>()
{
public void done(List<ParseObject> followinglist, ParseException e)
{
for (ParseObject following : followinglist)
{
ParseObject follow = following.getParseObject("following");
ParseObject friend=following.getParseObject("friends");
}
}
});
I have the following code in java:
try {
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
session=sessionFactory.openSession();
Query userQuery=session.createQuery("select u.userId, u.username,p.profileContent from User as u inner join u.profiles as p");//, p.profileContent
List userList=userQuery.list();
for(int i=0;i<userList.size();i++){
System.out.println(userList.get(i));
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
session.flush();
session.close();
}
I am trying to display the result of the query but only the object is displayed. Can you suggest me the way to display the contents of the objects. Currently i am getting result like:
[Ljava.lang.Object;#64bef361
for (Object o : userList) {
Object[] row = (Object[]) o;
System.out.println(Arrays.toString(row));
}
But you should probably use a debugger instead of cluttering your code with such loops.
whenever you try to print any object reference, it's toString() method is called. Now, suppose your userList is of type User. You have not overridden toString() method in your User class. So, what's happening currently is toString() method of object class is called.The Object class has implemented this method in such a way that it prints it's fully qualified package name and it's hashcode.
So, simply override this toString() method in your User class and it will start printing entire data as you have configured in this method. You can manually override this method, or if you have an IDE line netbeans or eclipse, just right click anywhere in the java file and select generate ToString method.
In Java, good programming practice is to override Object.toString() So that you avoid this problem. If you want more meaningful output then what you are getting, then adhere to the standards that are encouraged by the API.refer to the documentation when in doubt
I figured out the problem. I did not know the result of the query joining more than one tables will store the result as array of Objects class.
Query userQuery=session.createQuery("select u.userId, u.username,p.profileContent from User as u inner join u.profiles as p");//, p.profileContent
Iterator ite = userQuery.list().iterator();
while ( ite.hasNext() ) {
Object[] pair = (Object[]) ite.next();
Integer user = (Integer) pair[0];
String userName=(String) pair[1];
String profileContent=(String) pair[2];
System.out.println(user+" "+userName+" "+profileContent);
}
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?