3

我正在使用 sql2o 库编写数据库客户端。我的项目中有很多数据访问对象,所以我应该有很多类似的函数来访问表。例如,对于类Persons

public List<Persons> getPersonsData(){
   String sql = "SELECT * FROM " + PERSONS;
   try(org.sql2o.Connection con = sql2o.open()) {
      return con.createQuery(sql).executeAndFetch(Persons.class);
   }
}

有什么方法可以优化吗?我正在考虑使用泛型,但据我所知,没有办法获取泛型类的实例。真的不可能创造出这样的东西吗?

public class Getter<T> {
    public List<T> getGenericClass(){
        String sql = "SELECT * FROM " + T.tableName;
        try(org.sql2o.Connection con = sql2o.open()) {
            return con.createQuery(sql).executeAndFetch(T.class);
        }
    }
}
4

2 回答 2

3

我们设法创建了一个Store

 public class Store<T> {
    private T value;

    public void set(T object){
        value = object;
    }

    public T get(){
        return value;
   }
}

并修改您的 GenericClass

public class GenericClass{
     public <T> void storeGenericClass(Store<T> store, Class<T> clazz){
            String sql = "SELECT field1, field2 FROM MYTABLE WHERE ID = 1";
            try(org.sql2o.Connection con = sql2o.open()) {
                store.set(con.createQuery(sql).executeAndFetchFirst(clazz));
            }
        }

      public <T> void storeGenericClass(List<T> store, Class<T> clazz){
            String sql = "SELECT field1, field2 FROM " + 
              clazz.getName().toUpperCase();
            try(org.sql2o.Connection con = sql2o.open()) {
                store.addAll(con.createQuery(sql).executeAndFetch(clazz));
            }
        }

}

使用与 tableName 相同的 className 不是最佳做法。但是如果你用一张表来映射每个类,你可以这样做

  public class GenericClass{
    ...
     public <T> void storeGenericClass(List<T> store, Class<T> clazz){
            String sql = "SELECT field1, field2 FROM " + 
           clazz.getName().toUpperCase();
            try(org.sql2o.Connection con = sql2o.open()) {
                store.addAll(con.createQuery(sql).executeAndFetch(clazz));
            }
        }
     ...
}

实例化:

public class MyClass {

    public String field1, field2;
}


...
    GenericClass generic= new GenericClass(sql2o);
    Store<MyClass> store = new Store<>();
    generic.storeGenericClass(store, MyClass.class);
    MyClass retrieved = store.get();
    System.out.println("My Class fields are: "+retrieved.field1 + "-"+retrieved.field2);
...
于 2016-07-07T12:28:31.163 回答
3

我改进了@tonino 代码并删除了对 Store 类的需求。这是代码:

public <T> List<T> list(Class<T> clazz){ String sql = "SELECT * FROM " + getTablename(clazz); try(Connection con = sql2o.open()) { return con.createQuery(sql).executeAndFetch(clazz); } } public <T> T findById(Integer id, Class<T> clazz) { String sql = "SELECT *" + " FROM " + getTablename(clazz) + " WHERE id=:id"; try(Connection con = sql2o.open()) { return con.createQuery(sql) .addParameter("id", id) .executeAndFetchFirst(clazz); } } private String getTablename(Class clazz) { //This can be improved later with reflection return clazz.getSimpleName().toUpperCase(); }

于 2018-05-09T19:10:42.773 回答