Horje
Difference between JPA and Spring Data JPA

JPA provides specifications for persisting, reading, and maintaining data from Java objects to relational tables in a database. The JPA defines rules and principles for conducting standard interfaces. Spring data repository significantly reduces the extra code necessary to provide a data access layer for multiple persistence stores. Spring Data JPA is not a JPA provider rather. It is a library or framework offering an additional abstraction layer to the JPA provider line Hibernate.

In this article, we will discuss JPA vs Spring Data JPA.

JPA

JPA allows us to construct building blocks in an object-oriented syntax that is independent of the database we are using. To demonstrate, consider an employee table definition. Finally, we can define a table as a POJO using the @Entity annotation.

Java
@Entity // Add Entity annotation to mark the class as an entity
public class EmployeeEntity {
    // Class definition
}

public class CustomJpaDaoIntegrationTest {

    // EntityManagerFactory and EntityManager for custom persistence unit
    private final EntityManagerFactory customEmf = Persistence.createEntityManagerFactory("custom-pu-test");
    private final EntityManager customEntityManager = customEmf.createEntityManager();

    // Setup method to delete all employees before each test
    @Before
    public void setup() {
        deleteAllEmployees();
    }

    // Method to delete all employees from the database
    private void deleteAllEmployees() {
        // Begin transaction
        customEntityManager.getTransaction().begin();
        // Execute native SQL query to delete all employees
        customEntityManager.createNativeQuery("DELETE from EmployeeEntity").executeUpdate();
        // Commit transaction
        customEntityManager.getTransaction().commit();
    }

    // Method to save an employee entity to the database
    public void save(EmployeeEntity entity) {
        // Begin transaction
        customEntityManager.getTransaction().begin();
        // Persist the entity
        customEntityManager.persist(entity);
        // Commit transaction
        customEntityManager.getTransaction().commit();
    }

    // Method to update an employee entity in the database
    public void update(EmployeeEntity entity) {
        // Begin transaction
        customEntityManager.getTransaction().begin();
        // Merge the entity
        customEntityManager.merge(entity);
        // Commit transaction
        customEntityManager.getTransaction().commit();
    }

    // Method to delete an employee from the database by employee ID
    public void delete(Long employeeId) {
        // Begin transaction
        customEntityManager.getTransaction().begin();
        // Find and remove the entity by ID
        customEntityManager.remove(customEntityManager.find(EmployeeEntity.class, employeeId));
        // Commit transaction
        customEntityManager.getTransaction().commit();
    }

    // Method to update entities using CriteriaUpdate and return the number of updated records
    public int update(CriteriaUpdate<EmployeeEntity> criteriaUpdate) {
        // Begin transaction
        customEntityManager.getTransaction().begin();
        // Execute the CriteriaUpdate query and get the result
        int result = customEntityManager.createQuery(criteriaUpdate).executeUpdate();
        // Commit transaction
        customEntityManager.getTransaction().commit();
        // Clear the entity manager
        customEntityManager.clear();
        // Return the number of updated records
        return result;
    }
}

Spring Data JPA

Spring Data JPA is part of the wider Spring Data family, and it is designed as an abstraction layer over JPA. So we have all of JPA’s advantages plus Spring’s simplicity of development. For years, developers used boilerplate code to establish a JPA DAO with rudimentary functionality. It makes it easy to create Spring-powered apps with data access technologies.

Java
// Configuration class for custom Spring Data JPA settings
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = CustomRepository.class)
public class CustomSpringDataJpaConfig {

    // Bean definition for custom entity manager factory
    @Bean
    public LocalContainerEntityManagerFactoryBean customEntityManagerFactory(DataSource customDataSource) {
        // Creating entity manager factory bean
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        // Setting custom data source
        em.setDataSource(customDataSource);
        // Scanning packages for entity classes
        em.setPackagesToScan(EmployeeEntity.class.getPackage().getName());

        // Configuring JPA vendor adapter
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        // Setting Hibernate properties
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        em.setJpaProperties(properties);

        return em;
    }

    // Bean definition for custom transaction manager
    @Bean
    public PlatformTransactionManager customTransactionManager(LocalContainerEntityManagerFactoryBean customEntityManagerFactoryBean) {
        // Creating custom transaction manager
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(customEntityManagerFactoryBean.getObject());
        return transactionManager;
    }

    // Bean definition for custom data source
    @Bean
    public DataSource customDataSource() {
        return DataSourceBuilder.create()
          .driverClassName("org.h2.Driver")
          .username("customuser")
          .password("custompassword")
          .build();
    }

    // Bean definition for custom JPA query factory
    @Bean
    public JPAQueryFactory customJpaQueryFactory(EntityManager entityManager) {
        return new JPAQueryFactory(entityManager);
    }
}

Difference between JPA and Spring Data JPA

Below is the difference table of JPA and Spring Data JPA.

JPA

Spring Data JPA

JPA is a specification of Object Relational Mapper in Java.

Spring Data JPA is a simplified abstraction over JPA.

JPA can also manage transactions and is built on top of JDBC, allowing us to continue using our native database language.

Spring Data JPA adds a layer of abstraction to the JPA and more adaptable than JPA and provides simple repositories.

For query language, JPA is JPQL (Java Persistence Query Language)

For query language, Spring Data JPA is JPQL (Java Persistence Query Language)

JPA provides a JPA caching implementation technique for enhancing processes.

Spring Data JPA also provides a JPA caching process.

JPA is mainly depends on the JPA implementation.

Spring Data JPA also relies on JPA implementations.

JPA can work with any JPA-compliant implementation

Spring Data JPA can not work with any JPA-compliant implementation

JPA can be integrated with the Spring

Spring Data JPA can or can not be integrated with the Spring Data family.




Reffered: https://www.geeksforgeeks.org


Advance Java

Related
Configuring a Hikari Connection Pool with Spring Boot Configuring a Hikari Connection Pool with Spring Boot
Advanced Java Tutorial | Mastery in Java Programming Advanced Java Tutorial | Mastery in Java Programming
Top 30+ Java Microservices Interview Questions and Answers (2024) Top 30+ Java Microservices Interview Questions and Answers (2024)
Getting Started with Spring Boot and Eureka Service Registry Getting Started with Spring Boot and Eureka Service Registry
BeanDefinitionOverrideException in Spring Boot BeanDefinitionOverrideException in Spring Boot

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16