How to store classes into a database using JDBC

时间:2015-12-14 18:08:44

标签: java mysql jdbc

Starting point:
The program need to connect to a database. The data structure is unknown. The access data is provided in a seperate file.

The data needs to be analyzised and later updated.

Connection is made by using jdbc and the use of Statement, ResultSet and ResultSetMetaData.

For further manipulation of data, it is necessary to store them all in one object, a LinkedHashMap, key is the column index, value the column entries.

public class TableRepresentation {
   private final LinkedHashMap<Integer, DataType> tableData;

Because the data types differ, a new interface DataTypeis used.

public interface DataType {

  public void putDataToObject(int key, int value);

  public void putDataToObject(int key, String value);

  public void putDataToObject(int key, Date value);}

The idea is to use the factory pattern to create the Datatype objects at runtime. Next step is to add the data to each DataType object. There lies the problem.

By doing it this way, I of course have to implement each method in each class:

public class IntegerObject implements DataType{
  private final Map<Integer, Integer> attributeData;

  public IntegerObject(){
    attributeData = new LinkedHashMap<>();
  }

  /**
   * @return the attributeData
   */
  public Map<Integer, Integer> getAttributeData() {
    return attributeData;
  }

  @Override
  public void putDataToObject(int key, int value){
    attributeData.put(key, value);
  }       

  @Override
  public void putDataToObject(int key, String value) {
     throw new UnsupportedOperationException("Not supported yet.");
 }

  @Override
  public void putDataToObject(int key, Date value) {
     throw new UnsupportedOperationException("Not supported yet."); 
  }

which is a lot of unused and for sure dangerous code.

Question 1: Is there a way to overload methods, which are implemented from an interface?

Question 2: Is there a better way to achive the goal?

1 个答案:

答案 0 :(得分:1)

  

问题1:有没有办法重载从接口实现的方法?

所有这些方法签名都有点多余,您可以通过使用单个方法创建接口来概括:

public interface DataType {

  public void putDataToObject(int key, Object value);

}

然后你可以用任何你想要的方式覆盖它:

public class IntegerObject implements DataType{
  private final Map<Integer, Object> attributeData = new LinkedHashMap<>();

  public Map<Integer, Integer> getAttributeData() {
    return attributeData;
  }

  @Override
  public void putDataToObject(int key, Object value){
    attributeData.put(key, value);
  }  
}

现在,假设您只希望每个类实现putDataToObject 1次。如果您需要多个实现,那么使用Java中的instanceof关键字来分析不同的行为并不困难。

  

问题2:是否有更好的方法来实现目标?

是的,有一种标准方法可以在JDBC中使用SQLData接口执行此操作。

示例:

public class MyUser implements SQLData, Serializable
{
    private static final long serialVersionUID = -4235126659654360181L;
    public String name;
    public String address;
    public String phone;
    private String sql_type;

    public MyUser(String name, String address, String phone) {
        this.name = name;
        this.address = address;
        this.phone = phone;
    }

    @Override
    public String getSQLTypeName() throws SQLException {
        return sql_type;
    }

    @Override
    public void readSQL(SQLInput stream, String typeName) throws SQLException {
        sql_type = typeName;
        name = stream.readString();
        address = stream.readString();
        phone = stream.readString();
    }

    @Override
    public void writeSQL(SQLOutput stream) throws SQLException {
        stream.writeString(name);
        stream.writeString(address);
        stream.writeString(phone);
    }
}

然后,它很容易阅读和写入数据库:

// Writing an object to a database
PreparedStatement pstmt = conn.prepareStatement("insert into MY_USER_TABLE values(?,?)");
pstmt.setInt(1, 1);
pstmt.setObject(2, new MyUser("Alice", "aAddress", "111-1111"));
pstmt.addBatch();
pstmt.executeBatch(); // Insert the users
pstmt.close();

// Reading an object from a database
Statement stmt = conn.createStatement();
stmt.execute("select * from MY_USER_TABLE");
ResultSet rs = stmt.getResultSet();
rs.next();
MyUser userFromDB = rs.getObject(2, MyUser.class);
rs.close();
stmt.close();