java - How can i rewrite this methods without duplication? -
how can make code without duplication? methods similar.
method create phone numbers:
private list<string> createphonenumbers(string sqlstatement, long id) { list<string> phones = new arraylist<>(); try (preparedstatement statement = this.connection.preparestatement(sqlstatement)) { statement.setlong(1, id); try (resultset resultset = statement.executequery()) { while (resultset.next()) { phones.add(resultset.getstring("phonenumber")); } return phones; } } catch (sqlexception e) { e.printstacktrace(); return null; } }
method create friend list:
private list<account> createfriendlist(string sqlstatement, long id) { list<account> friends = new arraylist<>(); try (preparedstatement statement = this.connection.preparestatement(sqlstatement)) { statement.setlong(1, id); try (resultset resultset = statement.executequery()) { while (resultset.next()) { friends.add(createsimpleelement(resultset)); } return friends; } } catch (sqlexception e) { e.printstacktrace(); return null; } }
method create group list:
private list<group> creategrouplist(string sqlstatement, long id) { list<group> groups = new arraylist<>(); try (preparedstatement statement = this.connection.preparestatement(sqlstatement)) { statement.setlong(1, id); try (resultset resultset = statement.executequery()) { while (resultset.next()) { groups.add(creategroupfromresultset(resultset)); } return groups; } } catch (sqlexception e) { e.printstacktrace(); return null; } }
this bad solution.
//field values: 1- create string, 2 - createaccount, 3 - creategroup private <e> list<e> createlist(string selectsql, long id, int field) { list<e> list = new arraylist<>(); try (preparedstatement statement = this.connection.preparestatement(selectsql)) { statement.setlong(1, id); try (resultset resultset = statement.executequery()) { while (resultset.next()) { switch (field) { case 1: list.add((e) resultset.getstring("phonenumber")); break; case 2: list.add((e) createsimpleelement(resultset)); break; case 3: list.add((e) creategroupfromresultset(resultset)); break; } } return list; } } catch (sqlexception e) { e.printstacktrace(); return null; } }
what can read solve similar problems in code?
sounds me should check out spring jdbc , it's callback-based jdbctemplate
approach. abstracts boilerplate (database connections, transactions, exception translation etc.) away , lets focus on application code.
sample:
list<actor> actors = this.jdbctemplate.query( "select first_name, last_name t_actor", new rowmapper<actor>() { public actor maprow(resultset rs, int rownum) throws sqlexception { actor actor = new actor(); actor.setfirstname(rs.getstring("first_name")); actor.setlastname(rs.getstring("last_name")); return actor; } });
Comments
Post a Comment