How to Customize Java HasMap RowMapper Dynamically covert from Selected SQL Query to Jason Data as API response

Test Controller Example


In this tutorial, I'm going to show you how to create Customize Java HasMap RowMapper Dynamically covert from Selected SQL Query to Jason Data as API response.

By using this class will help you to convert data from your sql query dynamically without using model class (DTO)

And give you the example of class implementation to call that Has Map RowMapper class with SQL Query.



In this example, I'm going to use NamedParameterJdbcTemplate in Spring Framework as Data Source Connection. And I will show you how to configue it with Database in order to cannect with data from your table.


NamedParameterJdbcTemplate:

org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate

Template class with a basic set of JDBC operations, allowing the useof named parameters rather than traditional '?' placeholders. 

This class delegates to a wrapped JdbcTemplateonce the substitution from named parameters to JDBC style '?' placeholders isdone at execution time. It also allows for expanding a java.util.Listof values to the appropriate number of placeholders. 

The underlying org.springframework.jdbc.core.JdbcTemplate isexposed to allow for convenient access to the traditional org.springframework.jdbc.core.JdbcTemplate methods. 

The Has Map Helper Rowmapper class with use Map, HashMap, ResultSet, ResultSetMetaData, SQLException and stream.Collectors. if you want to know more about all of these java method/Object,

you can google it to read and practice more. However, I will show some of the short importand about all of these method step by step.


ResultSet: java.sql.ResultSet

A table of data representing a database result set, whichis usually generated by executing a statement that queries the database. 

A ResultSet object maintains a cursor pointingto its current row of data. Initially the cursor is positionedbefore the first row. 

The next method moves thecursor to the next row, and because it returns falsewhen there are no more rows in the ResultSet object,it can be used in a while loop to iterate throughthe result set. 


ResultSetMetaData: java.sql.ResultSetMetaData

An object that can be used to get information about the typesand properties of the columns in a ResultSet object.The following code fragment creates the ResultSet object rs,creates the ResultSetMetaData object rsmd, and uses rsmdto find out how many columns rs has and whether the first column in rscan be used in a WHERE clause. 

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
boolean b = rsmd.isSearchable(1);


SQLException: java.sql.SQLException

An exception that provides information on a database accesserror or other errors. 

Each SQLException provides several kinds of information: 

• a string describing the error. This is used as the Java Exceptionmessage, available via the method getMesasge. 

• a "SQLstate" string, which follows either the XOPEN SQLstate conventionsor the SQL:2003 conventions.The values of the SQLState string are described in the appropriate spec.The DatabaseMetaData method getSQLStateTypecan be used to discover whether the driver returns the XOPEN type orthe SQL:2003 type. 

• an integer error code that is specific to each vendor. Normally this willbe the actual error code returned by the underlying database. 

• a chain to a next Exception. This can be used to provide additionalerror information. 

• the causal relationship, if any for this SQLException. 

See Also:Serialized Form


HashMap: java.util.HashMap

Hash table based implementation of the Map interface. Thisimplementation provides all of the optional map operations, and permits null values and the null key. (The HashMapclass is roughly equivalent to Hashtable, except that it isunsynchronized and permits nulls.) This class makes no guarantees as tothe order of the map; in particular, it does not guarantee that the orderwill remain constant over time. 

This implementation provides constant-time performance for the basicoperations (get and put), assuming the hash functiondisperses the elements properly among the buckets. Iteration overcollection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the numberof key-value mappings). Thus, it's very important not to set the initialcapacity too high (or the load factor too low) if iteration performance isimportant. 


Map: java.util.Map

An object that maps keys to values. A map cannot contain duplicate keys;each key can map to at most one value. 

This interface takes the place of the Dictionary class, whichwas a totally abstract class rather than an interface. 

The Map interface provides three collection views, whichallow a map's contents to be viewed as a set of keys, collection of values,or set of key-value mappings. The order of a map is defined asthe order in which the iterators on the map's collection views return theirelements. Some map implementations, like the TreeMap class, makespecific guarantees as to their order; others, like the HashMapclass, do not. 



Stream.Collectors: java.util.stream.Collectors

Implementations of Collector that implement various useful reductionoperations, such as accumulating elements into collections, summarizingelements according to various criteria, etc. 

The following are examples of using the predefined collectors to performcommon mutable reduction tasks: 


Now Let's see the HasMap RowMapper Class here: 


Let's create Java DAO class implementation to call HaMap RowMapper with SQL Query example.


Then, let's create service implement class to call the DAO class.


Lastly, Let's create a controller class to call that service implementation above.


Note: This example of api creation to use the HasMap RowMapper class, I did not using model DTO class.
I have just created Controller class to call servcie, Service Implementation class to call DAO and lastly DAO class to connect with Datasource from Table for response data from API request. 
That's it.

Last recomendation: 

You can use postman to request API.


Related Article

- CRUD Rest API using node js, express, and postgresql - Complete setup and config multi module spring maven project

Previous Post Next Post