前几天,我发现了有关DbUtils的信息,因此我跳入了一个项目进行测试。我创建了一个名为Tag的类,如下所示。
package io.sharpsoft.hooke.rest.models;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Tag implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8040690224162074105L;
private int id;
private String name;
public Tag() {}
public Tag(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "ID: " + this.getId() + ", Name: " + this.getName();
}
}
我的数据库中有一个名为TAGS的表,我要做的就是创建一个获取所有这些TAGS的函数。这是我写的功能:
public static List<Tag> getAllTags() throws SQLException {
Connection conn = null;
QueryRunner runner = new QueryRunner();
try {
DbUtils.loadDriver(Constants.JDBC_DRIVER);
conn = DriverManager.getConnection(ConfUtils.getDbUrl(), ConfUtils.getDbUser(), ConfUtils.getDbPass());
ResultSetHandler<List<Tag>> resultHandler = new BeanListHandler<>(Tag.class);
List<Tag> tags = runner.query(conn, "select * from TAGS", resultHandler);
System.out.println("Tags");
for (Tag tag : tags) {
System.out.println("ID: " + tag.getId() + ", Name: " + tag.getName());
}
return tags;
} finally {
DbUtils.close(conn);
}
}
问题是BeanListHandler无法将结果集条目正确映射到我的对象中。这就是我得到的:
ID: 0, Name: null
ID: 0, Name: null
ID: 0, Name: null
ID: 0, Name: null
ID: 0, Name: null
ID: 0, Name: null
ID: 0, Name: null
ID: 0, Name: null
ID: 0, Name: null
任何帮助将不胜感激!谢谢!