Not really, no. You need code of about that level of complexity. That's because you need separate code for each field of your model object.
However your code which decides whether to precede a comparison with "where" or "and" is a problem, because (1) it's too complicated, and (2) it won't work. I suggest that you need a local boolean variable which keeps track of whether you've used "where" or not. Use that to output "where" before your first comparison and "and" before the others. That's much simpler than your code which compares longer and longer lists of fields to null, and it should work better too. Your existing code can easily produce invalid SQL.
(Yes, I'm aware that your code isn't meant to be production-level code yet, so it wouldn't be surprising to find flaws in it. I'm just pointing out what I consider to be a major flaw.)
Joined: Nov 22, 2012
@ Mr.Paul Clapham,
Thank You very much.
Yes Mr.Paul ,The code whatever i wrote here ,it produces invalid SQL query(it throws exception),
Here I forgot to enclose single quotes ..
Yes, that's the sort of error it's easy to make when you build an SQL statement using string concatenation like that. Normally I would recommend using a PreparedStatement, which simplifies building the SQL and also protects against SQL injection attacks.
However in this case if you do that then your code will need two phases: the first would build the SQL for the PreparedStatement, and then the second would fill in the parameters. Both phases would have to do similar things, i.e. going through the fields of your model object and executing code if the field wasn't null. That's a considerable increase in complexity, so for now I would suggest you don't bother with that. Get a working version of what you have so far. But if the code becomes production code, i.e. not just a school exercise but real-life code, then I would suggest revisiting it and using PreparedStatement with the added complexity.
subject: How to Check whether an object contains data/values or not?