dimanche 19 avril 2020

how to insert data into H2 database using reflection API

I have a Person class anootated with @PrimaryKey and @Column

    public class Person {

    @PrimaryKey(name = "p_id")
    private Integer id;

    @Column(name = "c_name")
    private String name;

    @Column(name = "c_age")
    private Integer age;
    }

Following is the persist method:

   public void persist(T t) throws IllegalArgumentException, IllegalAccessException, SQLException {
    // TODO Auto-generated method stub
    MetaModel metaModel = MetaModel.of(t.getClass());
    String sql = metaModel.buildInsertRequest();

    try(PreparedStatement statement = prepareStatementWith(sql).andParameters(t)){
        statement.executeUpdate();  
    }

}

    private PreparedStatementWrapper prepareStatementWith(String sql) throws SQLException {
    // TODO Auto-generated method stub

    Connection con = buildConnection();
    PreparedStatement statement = con.prepareStatement(sql);

    return new PreparedStatementWrapper(statement);
}

    private class PreparedStatementWrapper{

    private PreparedStatement statement;
    public PreparedStatementWrapper(PreparedStatement statement) {
        // TODO Auto-generated constructor stub
         this.statement = statement;
    }

Here. returning the sql query

   public String buildInsertRequest() {
    // insert into Person(id, name, age) values(?, ?, ?)
    String pkColumnName = getPrimaryKey().getName();
    List<String> columNames = getColumn().stream().map(c -> c.getName()).collect(Collectors.toList());
    columNames.add(0, pkColumnName);
    String columnElement = String.join(", ", columNames);

    int numberOfColumns = getColumn().size() + 1;
    String questionMarkElement = IntStream.range(0, numberOfColumns)
                                            .mapToObj(index -> "?")
                                            .collect(Collectors.joining(", "));
    return "INSERT into " + this.clss.getSimpleName() + "(" + columnElement + ") values (" + questionMarkElement + ")";
}

   Here adding the parameter

   public PreparedStatement andParameters(T t) throws SQLException, IllegalArgumentException, IllegalAccessException {
        // TODO Auto-generated method stub

        MetaModel metaModel = MetaModel.of(t.getClass());
        Class<?> pkType = metaModel.getPrimaryKey().getType();
        if(pkType == Integer.class) {
            Integer id = idGenerator.incrementAndGet();
            statement.setInt(1, id);    
            Field field = metaModel.getPrimaryKey().getField();
            field.setAccessible(true);
            field.set(t, id);
        }
        for(int columnIndex = 0; columnIndex < metaModel.getColumn().size(); columnIndex++) {
            ColumnField columnField = (ColumnField) metaModel.getColumn().get(columnIndex);
            Class<?> fieldType = columnField.getType();
            Field field = columnField.getField();
            field.setAccessible(true);
            Object value = field.get(t);
            if(fieldType == Integer.class) {
                statement.setInt(columnIndex + 2,(Integer) value);
            } else if(fieldType == String.class) {
                statement.setString(columnIndex + 1, (String)value);
            }
        }
        return statement;
    }

I am getting error in prepareStatementWith(sql) method, it's not reurning the new PreparedStatementWrapper instead it's throwing exception Exception in thread "main" org.h2.jdbc.JdbcSQLException: Table "PERSON" not found; SQL statement: INSERT into Person(p_id, c_name, c_age) values (?, ?, ?)

Following is the connection details:

    public Connection buildConnection() throws SQLException {
    Connection con = 
            DriverManager.getConnection("jdbc:h2:C:\\Users\\biplab.musib\\eclipse-workspace\\ReflectionProject\\db-files\\db-files", "sa", "");
    return con;

JDBC url in H2 promp : jdbc:h2:C:\Users\biplab.musib\eclipse-workspace\ReflectionProject\db-files\db-reflection

can someone help me here





Aucun commentaire:

Enregistrer un commentaire