java 对象数据映射,将行数据从SQL数据映射到Java对象

博主推荐使用Spring JDBC库来替代手动的数据库查询映射。Spring JDBC提供连接管理,减少资源关闭的工作,并且包含便利的行映射功能,使得从ResultSet到自定义Java对象的转换更加简洁。通过引入Spring JDBC,可以降低代码的冗余,方便地处理不断增加的列,提高代码维护性。
摘要由CSDN通过智能技术生成

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.

For example:

I have a "Student" class with instance fields "FNAME", "LNAME", "GRADE" and appropriate getter and setter methods for each.

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.

解决方案

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.

We've retrofitted legacy code with Spring JDBC with little trouble.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值