Optimize PreparedStatements for either one or multiple queries- Java & MySQL -
if i'm not mistaken, preparedstatement destroyed cache once connection closed. @ moment app setup have function pojo objects database based on single pojo object passed in. have function id's of objects in table cases need list, , in while loop of function entire objects 1 @ time.
however doing doesn't take advantage of cached queries right? best way have generic getter sql function can make use of cached preparedstatements if list of items or single item? in php can checking if passed in param array or not, java requires define param object.
so example, let's users, here have:
//get user object public user getuser(user user) throws sqlexception { connection connection = connectionwrapper.getconnection(); string query = "select firstname, lastname users userid = ?"; preparedstatement statement = connection.preparestatement(query); statement.setint(1, user.getuserid()); resultset rs = statement.executequery(); if (rs.next()) { //get database details , set object } rs.close(); statement.close(); connection.close(); } //get users public list<user> getallusers() throws sqlexception { list<user> userarr = new arraylist<user>(); connection connection = connectionwrapper.getconnection(); string query = "select userid users"; preparedstatement statement = connection.preparestatement(query); resultset rs = statement.executequery(); while (rs.next()) { int id = rs.getint("userid"); user user = new user(id); getuser(user); userarr.add(user); } rs.close(); statement.close(); connection.close(); return userarr; }
it nice able getuser function handle both individual object case above , array case array of user objects (with userid's set) passed in , loops through array objects before closing connection. there non-messy way or should pass user array getuser function in cases, if it's one?
if you're after performance, executing 5 queries find 5 users given array of 5 ids not best solution. you'd better execute single query loads users @ once, using
select firstname, lastname users userid in (?, ?, ?, ?, ?)
similarly, getallusers()
method extremely inefficient. should execute single query, instead of executing query ids, , query every id found.
Comments
Post a Comment