Parse Query on Array Values - java

I'm trying to make a query to get certain objects. The thing is.. I don't know how to make a query to get object that match an array. The User can be a member of multiple Groups, so the names of these groups are stored in User.groups as an array. I am trying to get all the objects of the class 'Group' that the current user is a member of. I came up with this:
ParseQuery query1 = ParseQuery.getQuery("_User"); //selects User Class
query1.whereEqualTo("username", current_user.toString()); //selects current user
query1.include("groups"); //include 'groups' of type array with names of the groups that the user is a member of
ParseQuery query2 = ParseQuery.getQuery("Group"); //select Groups Class
query2.whereContainedIn("group_name", ?); //<-- Get objects where group_name matches a value in the User.groups
The last line of code is obviously not the way to do it. I already looked at the Parse Guide! Help is much appreciated!

After some digging and testing I came up with a solution. It wasn't that difficult actually..
ParseQuery<ParseObject> groupQuery = new ParseQuery<ParseObject> ("Group");
groupQuery.include("array");
groupQuery.whereEqualTo("array", ParseUser.getCurrentUser().getUsername());
This code selects the class 'Group' which has an array with all the usernames in it called 'members' that looks like: ["user1","user2",".."]. This array is included. The last line of code selects all the objects that the user is a member of.

Related

how to map query result to string array in java

select id,name,salary,city,state,country from employee where name like '%a%';
I need to map above query result to String array, position 0 always id, position 1 always name ...... position 5 always country.
Using JPA or MyBatis is there a way we can dynamically map the select query values into fixed position string array ?
I've never personally used JPA, but - after reading through it a bit - believe this should be correct.
TypedQuery<Object[]> query = entityManager.createQuery(
"SELECT id,name,salary,city,state,country FROM employee WHERE name LIKE '%a%'", Object[].class);
List<Object[]> results = query.getResultList();
where (Integer) results.get(index)[0] = id, (String) results.get(index)[1] = name, etc.
You can change Object[] to String[] if you would like an array of Strings.
Why do you want to use String array?
It is better to use an object list instead. It will be easier to get city of an employee using employee.getCity() versus array[3].
It makes for more readable code as well.
To use an object list, you need to create a model for your employee and annotate with #Entity and create a repository for that entity. JPA documentation should help do this easily

Use Parse.com and Android, how can I get a list of Games that a pair of Players share?

I am making a two-player for Android using Parse.com. I'm determining which two players are in the game by introducing a Game table on Parse.com, with an Array of the userIds of the players of the game.
I need to query Parse.com for a list of all the games shared by two given players. I thought something like this would do the trick.
String[] userIds = new String[] {player1, player2};
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Game");
query.whereEqualTo("players", userIds);
The problem is, I don't know the order of the Array of players. So about half of the time, the order will be wrong I won't get the correct result from this query. I'll get that no game exists between the two players.
So my idea to solve this was to also query for a reversed array, then OR the two queries together.
String[] reversedUserIds = new String[] {player2, player1};
ParseQuery<ParseObject> query2 = new ParseQuery<ParseObject>("Game");
query2.whereEqualTo("players", reverseUserIds);
List<ParseQuery<ParseObject>> queryList = new ArrayList<ParseQuery<ParseObject>>();
queryList.add(query);
queryList.add(query2);
ParseQuery<ParseObject> mainQuery = ParseQuery.or(queryList);
However, when I run mainQuery.find(), I get an error that looks like this:
java.lang.IllegalArgumentException: invalid type for ParseObject: class [Ljava.lang.String;
Instead of simply returning a list of all the games that both players are playing with each other.
You could try to force the IDs pair to be always ordered, for example doing player1.compareTo(player2). Then you only need to query with the right order.

fetching records from database based on variable number of inputs from from

I have a form with 8 fields and based on the values entered in them I have have to fetch the records from the DataBase. Now the problem is out of the 8 fields the user may fill any number of fields and that too in any order for example the user may fill fields 1,4 and 6 or he may fill 1 and 7 or he may fill all of them (of course he has to fill at least one field)... Now how will I write a query which will work for any number and order of input parameters? and also because this query will be used in reporting(iReport) I am not allowed to write any code with it , it has to be a SQL query. Any ideas
Thanks
there are a number of ways to do this. I have a blog post about doing something like this in a Microsoft SQL (T-SQL) stored procedure at http://code.scottshipp.com/2013/03/29/tutorial-stored-procedures-with-truly-optional-parameters/ but it is likely that you will want to do something more complex and/or you are not using MS SQL Server. You may have to write the query fragments yourself. My suggestion is to do something like the following:
Once the form is submitted, loop through the various fields in the form, and check if their values are empty or not.
For those that are not empty, add a string containing an appropriate corresponding query fragment to some collections object, like an ArrayList. Do not include "AND" or "OR" directly in this string. If you need to keep track of whether this query fragment gets "AND"ed or "OR"ed with other query fragments, track that in a separate collections object. The "query fragment" I'm talking about is what would show up in the "where __" portion of your SQL query. For instance, say the search was for someone's last name. The query fragment you add is a string that says "lastName='" + lastNameField.value() + "'".
Once you have iterated through all the various fields in the form and have a final collections object full of query fragments, construct the final SQL statement from it. Iterate through your collections object (ArrayList in this example) and connect each one with the appropriate "AND" or "OR". Say your ArrayList has the three fragments "firstName='Joe'", "middleName='Q.'", "lastName='Public'". Use a StringBuilder to keep adding these fragments together into a final where clause: "firstName='Joe' AND middleName='Q.' AND lastName='Public'"...you may want to change these to a "LIKE" style query with wildcard characters.
You now have everything you need to create the final select statement. Issue it to the database and retrieve your results!

How to search strings in java

I currently search the database to get certain results with a pl/sql query like this:
SELECT
*
FROM
citrostats cs
WHERE
(
trim(upper(cs.name)) like trim(upper('%'|| ? ||'%'))
OR
trim(upper(cs.UCODE)) like trim(upper('%'|| ? ||'%'))
)
ORDER BY NAME DESC
I reorganised this, and fetched all rows into Lists of Objects with have the respective columns as String attributes.
What I need is a java code that would search attributes that are String type to give the same set of objects as results like this query has.
Anyone can help?
There is String#contains:
if (name.toUpperCase().contains(uppercasedSearchString))
Since you are doing this in a loop, save work by upper-casing the search string only once before the loop.

Processing mysql records in java

I have a table with scores that contestants get after the complete a quiz. I then select the max(points) for each user and i group by user
select distinct userName, max(points) as numpoints
from tblscore
group by userName
order by numpoints desc
this gives me the order of all the highest scores for the user. i want to store these records in an array and process it, i want to rank each record plus i want to display records where the users have a tie. How can this be achieved? how will the array be set up and processed to cater for this.
Create a class (e.g. UserScore) with two fields - username and points
Get the ResultSet for the desired query (via a Statement)
Define a List<UserScore> list = new ArrayList<UserScore>
Loop the result set, using while (rs.next()) and on each iteration create a new instance of the UserScore class, set both of its fields (e.g. userScore.setPoints(rs.getInt("numpoints")), and then add the object to the list
If you can do with a List - go with it. If you really need an array - use list.toArray(..)
Alternatively, you can use apache commons-dbutils, and after you create the UserScore class, you just call:
List<UserScore> list = new BeanListHandler(UserScore.class).handle(resultSet);
Note that in this case your fields should be called the same way as your returned column names/aliases. You can also use the ArrayListHandler, which, instead of a list of the defined class, will give you a List<Object[]> where each column will be an element in the array.

Categories