java - How can I reduce code duplication in my database access layer? -


i new java , i'm trying implement basic database access layer. i'm using apache dbutils reduce jdbc boilerplate code , working well.

the problem implementation uses separate class crud each table in database , feels wrong duplicating functionality.

is acceptable design , if not can reduce code duplication?
refactor solution use generics in fashion?

i realize use orm (mybatis, hibernate etc) solution try stick dbutils , plain jdbc if can it.

just clarification:
lets have 2 tables...

---------------------   user    |  file   ---------------------   userid  |  fileid   name    |  path   age     |  size   ---------------------   

in current solution create 2 classes (userstore, filestore) , each class implement similar basic crud methods:

protected boolean create(user newuser) {     queryrunner run = new queryrunner(datasource);     try      {         run.update("insert user (name, age) " +                 "values (?, ?)", newuser.getname(), newuser.getage());      }     catch (sqlexception ex)      {         log.logexception(ex);         return false;     }     return true; }  protected user read(int userid) {     try     {         user user = run.query("select * user userid = ? ", userid);         return user;     }     catch (sqlexception ex)      {         log.logexception(ex);         return null;     } }  protected update(user user) {     ... perform database query etc }  protected delete(int userid) {     ... perform database query etc } 

you asked how template method. here example how it:

public class abstractdao<t> { private string table; private string id_field;  public abstractdao(string table, string id_field){ this.table = table; ... }  public t read(int id){     try {     t user = run.query("select * "+ table + " "+id_field +" = ? ", id);     return user; } catch (sqlexception ex)  {     log.logexception(ex);     return null; } } 

this 1 looks easy, how create?

public boolean create(t user){     queryrunner run = new queryrunner(datasource); try  {     run.update("insert "+table+ getfields() +             "values " + getparameters(user));  } catch (sqlexception ex)  {     log.logexception(ex);     return false; }      return true; }  protected abstract string getfields();  protected abstract string getparameters(t user); 

ugly, , insecure, okay transmitting idea.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -