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.
RowMapper<T> interface is used by JdbcTemplate for mapping rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of mapping each row to a result object.
Object-Relational Mapping or ORM is a technique for converting data between Java objects and relational databases.
But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we can make this object as updatable by: Statement stmt = con. createStatement(ResultSet.
To map a single result row to our java object Statewe will call jdbcTemplate.queryForObjectpassing in the sql to execute and the StateRowMapper. Running the junit testthe output shows that the sql is executed and the Statewas logged.
Example of SQL Mapping Let us take a simple mapping example where we will take the class model and will see an equivalent physical data model in which each attribute of the class model will be mapped to a single column in the physical data model. Consider an example where we will be storing the class details of the stock at a shop.
Mapping SQL and Java Data Types SQL data type Java data type Java data type DECIMAL java.math.BigDecimal BIT boolean Boolean TINYINT byte Integer SMALLINT short Integer 16 more rows ...
You could use an ORM like one of the JPA providers e.g. Hibernate. This lets you set up mappings between your objects and your tables.
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.
Spring JDBC Presentation PDF
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With