将行数据从SQL数据映射到Java对象 [英] Mapping a row from a SQL data to a Java object
问题描述
我有一个Java类,其实例字段(和匹配的setter方法)与SQL数据库表的列名匹配。我想优雅地从表中获取一行(到ResultSet中)并将其映射到该类的实例。
I have a Java class with instance fields (and matching setter methods) that match the column names of a SQL database table. I would like to elegantly fetch a row from the table (into a ResultSet) and map it to an instance of this class.
例如:
我有一个学生课程,其实例字段为FNAME,LNAME,GRADE,并为每个实例提供适当的getter和setter方法。
I have a "Student" class with instance fields "FNAME", "LNAME", "GRADE" and appropriate getter and setter methods for each.
我还有一个带有三个同名列的SQL表。
I also have a SQL table with three columns of the same name.
现在我正在做这样的事情:
Right now I am doing something like this:
rs = statement.executeQuery(query);
Student student = new Student();
student.setFNAME(rs.getString("FNAME"));
student.setLNAME(rs.getString("LNAME"));
student.setGRADE(rs.getString("GRADE"));
这样做的方式必须简洁,对吧?当我添加列时,这可能会变得非常烦人和混乱。
There has to be a less verbose way of doing this, right? As I add columns this might get really annoying and messy.
推荐答案
我建议使用 Spring JDBC 。您不需要使用Spring的其余部分来使用他们的JDBC库。它将为您管理连接(不再关闭连接
,语句
或 ResultSet
)并且有很多便利,包括行映射。
I recommend using Spring JDBC. You don't need to use the rest of Spring to use their JDBC library. It will manage connections for you (no more closing Connection
, Statement
, or ResultSet
) and has many conveniences, including row mapping.
我们用Spring JDBC改进遗留代码没什么问题。
We've retrofitted legacy code with Spring JDBC with little trouble.
以下是Spring JDBC概述的演示文稿(PDF)。虽然没有让Spring注入依赖项,但它已经存在了几年,但仍然基本相同。
Here is a presentation (PDF) of an overview of Spring JDBC. It's a few years old but it still works essentially the same, even without letting Spring inject the dependencies.
这篇关于将行数据从SQL数据映射到Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!