Spring Boot – Spring JDBC vs Spring Data JDBC
Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect “mysql-connector-java”. Let us see how a pom.xml file of a maven project looks like.
We need a MODEL class to start
Implementation of DAO Interface:
Spring Data JDBC
It belongs to the Spring Data family. Basically, it provides abstractions for the JDBC-based Data Access Layer. It provides easy to use Object Relational Mapping (ORM) framework to work with databases. It can support entity objects and repositories. Because of this, a lot of complexities are reduced. The data access layer is simple. Hence JPA features like Lazy Loading, caching of entities, etc. are omitted. Because of this JDBC operations on the entities are taken care of well. Let us see what are the dependencies needed for Spring Data JDBC in the Spring Boot maven project.
Let us see what are the dependencies needed for Spring Data JDBC in the Spring maven project.
For making the entity, we need to use a POJO(Plain old java object). Spring Data JDBC can map our POJO to a database table. The following key points need to be observed
- Created POJO needs to match with the database table. If not, it uses @Table annotation and this helps to refer to the actual table name.
- @Id annotation is required to identify the primary key
- It is a good practice that all the persistence fields in the POJO and database table columns need to match. Otherwise, @Column annotation is helpful to provide column names.
Sample POJO class
For a POJO class, it is not mandatory to have
- A parameterized constructor.
- Access methods.
Repository Interface along with Query methods and @Query annotations are supported. Created repositories can be a sub-interface of CrudRepository.
The named query can be constructed as
Difference Between Spring JDBC and Spring Data JDBC
Spring Data JDBC
|Spring JDBC is a Model class.||Spring Data JDBC is a POJO class.|
|Getter and setters are mandatory.||Getter and setters are not mandatory.|
|The parameterized constructor will be helpful.||The parameterized constructor may not be helpful.|
|There is no specific annotation is required. The only thing is we should have equal attributes match with the DB table and each attribute should have a getter and setter.||@Table, @ID, and @Column annotations are helpful to mention for direct connection with the database.|
|Data Access Layer is specified with the interface and its implementation.||Data Access Layer is simple and it omits lazy loading, cache implementation, etc., which is there in JPA(Java Persistence API).|