Reputation: 743
I am trying to generate a where query through ormlite.
eg:Where name='Ärer' and (type='tt1' or type='tt2')
But the result always apppears like this
SELECT * FROM `Test` WHERE ((((((`name` = 'Arer' AND `type` = 'tt1' ) OR `type` = 'tt2' ) OR `type` = 'tt3' ) OR `type` = 'tt4' ) OR `type` = 'tt5' ) )
This is java code that i have used to generate the above query
Where<Test, Integer> whereStatement = queryBuilder.where();
int cnt = 0;
String[] channelArray = getChannelSettingsForDB();
whereStatement.eq(NAME, "Arer")
.and();
for (String channel : channelArray) {
if (channel != null) {
whereStatement.eq(TYPE, channel).or();
}
Kindly let me know the right way of usage to generate a where query like this
Where name='Ärer' and (type='tt1' or type='tt2' or type='tt3' or type='tt4' or type='tt5')
Upvotes: 0
Views: 364
Reputation: 116908
But the result always apppears like this
... OR
type
= 'tt2' ) ORtype
= 'tt3' ...
Everytime ORMLite adds an and()
or or()
it is going to add parenthesis to be specific about the and/or arguments. These methods take the previous clause and then do the operation with the next clause submitted.
In your case the first clause is the eq(NAME, "Arer")
which gets and-ed with the first eq(TYPE, channel)
. This is not what you want.
Kindly let me know the right way of usage to generate a where query like this ...
There are a couple of ways for you to do what you want to do. The first way uses the where.or(int)
feature which absorbs a number of clauses and separate them via OR
.
whereStatement.eq(NAME, "Arer");
int channelCount = 0;
for (String channel : channelArray) {
if (channel != null) {
whereStatement.eq(TYPE, channel);
channelCount++;
}
}
if (channelCount > 0) {
// or the last X clauses together
whereStatement.or(channelCount);
// and the channel ORs with the name
whereStatement.and(2);
}
However you might consider using the where.in(...)
method instead. It won't handle nulls however so you will have to copy your array into a list or other iterable:
List<String> channels = new ArrayList<String>(channelArray.length);
for (String channel : channelArray) {
if (channel != null) {
channels.add(channel);
}
}
if (!channels.isEmpty()) {
// the IN replaces a bunch of ORs
whereStatement.in(TYPE, channels);
// and the channel IN with the name
whereStatement.and(2);
}
For the various different ways to build queries, please RTFM:
Upvotes: 1