如何将POJO插入键值数据库table?

How to insert into a POJO into a key-value database table?

使用 Spring 将 POJO 插入到 键值 table 中的最简单方法是什么的 NamedParameterJdbcTemplate 无需手动循环 遍历每个字段并调用插入?

POJO:

class Person {
   String firstName;
   String lastName;
   int age;
   ...many more fields
}

键值 person_attributes Table:

attribute      | value
---------------------
 firstName     | Bob
 lastName      | Billy
 age           | 30

你可以使用 Jackson 的 ObjectMapper class 将 POJO 转换为键值对

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> personMap = mapper.convertValue(person, Map.class);

然后遍历每个映射条目并插入到数据库中

或者您可以使用 Apache commons beanutils

BeanPropertySqlParameterSource 是最好的方法:

Person person = .....

String sql = "insert into Person (first_Name, Last_Name, age) " + 
                   "values (:firstName, :lastName, :age)"; 
    namedParameterJdbcTemplate.update(sql, new BeanPropertySqlParameterSource(person)); 

这里有一个完整的例子: http://www.logicbig.com/tutorials/spring-framework/spring-data-access-with-jdbc/named-param-jdbc-template-example/