Featured
Relational Databases interactions with Java/Spring
2 min readOct 31, 2024
JDBC API
- Regardless of the framework abstractions or the you will be using the under the hood when interacting with a database using Java.
- It is JDK/JRE and we have to provide the desired database driver to work with this API.
- Database drivers primarily take care of opening socket connection with the underlying database and sending the queries through that connection. On the Java side what our surface area is with this JDBC API
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
conn = DriverManager.getConnection(
"jdbc:" + this.dbms + "://" +
this.serverName +
":" + this.portNumber + "/",
connectionProps);But this is not resource friendly to open and close socket connection here and there , and then comes the story of pooling. Central management of these said connections.
- But it is not resource friendly to open and close socket connection here and there , and then comes the topic of connection pooling. Central management of the said connections.
- Hikari CP is one of such popular implementations and on the optimal connection pool size, here is a big mamath for you( )
JPA
- What ? Just an specification → Popular implementations are Hibernate and Eclipselink
- Why ? It can be quite painful to interact with SQL queries and stuff with the low level JDBC API. It would be much better to establish a relationship with the underlying database model and our Java objects (Object Relational Mapping). Java side specification for ORM is JPA.
- How to become JPA compliant → Your library can save data to a database, can map java classes and tables and you can query and so on.. (please find the specifications ) → Ok mate! , now you’re JPA compliant.
Spring Data
- It’s another large-scale mammoth project under the Spring umbrella. You know that Spring is the smart framework that thinks about us and tries to make our lives easier by hiding lower-level APIs and providing tons of new features on top of them.
Spring Data JDBC
- Spring’s abstraction on top of JDBC API.
- With Spring Data JDBC, we have ORM mappings facilities, repositories, query annotations, and JdbcTemplate to interact with the database.
Spring Data JPA
- Spring’s abstraction on top of JPA.
- Provides repositories, query annotations and unlike Spring JDBC it provides method based query generation.