对MySQL表的简单JdbcTemplate.queryForMap()调用会产生这种奇怪的可解释行为。映射输出为get()返回null,并为keySet()和values()返回预期结果。
编辑: -张贴完整的课程代码 -使用RowMapper()实现的附加查询。
这是表模式:
create table Product(
id int not null primary key auto_increment,
`name` varchar(30),
price decimal(10,2)
);
mysql> select * from Product;
+----+--------+-------+
| id | name | price |
+----+--------+-------+
| 1 | iPhone | 10.00 |
+----+--------+-------+
1 row in set (0.00 sec)
完整的Java类:
package com.test1;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbcp2.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
/**
*
* @author user2176499
*
*/
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) throws Exception {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/testdb");
dataSource.setUsername("user");
dataSource.setPassword("password");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
Map<String, Object> row = jdbcTemplate.queryForMap("select * from Product where id=?", 1);
System.out.println(row.getClass());
System.out.println(row.keySet());
System.out.println(row.values());
System.out.println(row.containsKey("name"));
System.out.println(row.get("name"));
Iterator<String> iterator = row.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + " - " + row.get(key));
}
System.out.println("==================");
List<Map<String, Object>> rows = jdbcTemplate.query("select * from Product where id=?", new Object[] { 1 },
new RowMapper<Map<String, Object>>() {
@Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
return Map.ofEntries(Map.entry("id", rs.getInt("id")), Map.entry("name", rs.getString("name")),
Map.entry("price", rs.getDouble("price")));
}
});
System.out.println(rows);
}
}
输出:
class org.springframework.util.LinkedCaseInsensitiveMap
[id, name, price]
[1, iPhone, 10.00]
false
null
id - null
name - null
price - null
==================
[{name=iPhone, price=10.0, id=1}]
Spring版本:spring-jdbc-5.2.2-release