Tuesday 24 October 2023

How to Return DTO's from Native Queries in Spring Data JPA

          In this post, we will discuss how to return DTO's of non entity basis native query result from JPA repository method. JPA provides many implemented methods for database operations like findAll, findById and so on. If we use in-built JPA repository methods then corresponding entity to map with the query result. 
           
         In some of the scenario's need to use native query to join with multiple tables to get the required details. In such case, we should not have the entity mapping so need to discuss how to map the native query result to the entity or DTO. We can achieve this using interface based DTO. The interface based DTO approach, JPA repository query maps with DTO instead of entity so need to convert again entity object to DTO object.

Let's discuss this with code as below,

JPA repository with native query,

@Repository
public interface PropertyTaxRepository extends JpaRepository<PropertyTax, Long> {
	
     @Query(value=" SELECT z.zone as zoneName, pt.status as propertyType, SUM(pt.tax) as amountCollected "
		+ " FROM property_tax pt "
		+ " INNER JOIN zone z ON z.id=pt.zonal_classification "
		+ " group by z.zone, pt.status;", nativeQuery = true)
     public List<ReportDto> getTaxCollectedReport();
}

Created ReportDto interface with getter methods of the native query fields, there are three fields used in the select native query zoneName, propertyType and amountCollected. 

Interface based DTO class as follows,

public interface ReportDto {
      String getZoneName();
      String getPropertyType();
      BigDecimal getAmountCollected();
}

     If you have any questions or clarifications, please add comment in the comment section or send an email to anilnivargi49@gmail.com.

Thank you for visiting the blog.

Sunday 1 October 2023

Difference between @Component and @Bean annotation in Spring

          As we discussed about Stereotype annotations in one of the blog post, the @Component annotation is a  stereotype annotation in Spring. If you want to convert any java class as a Spring managed bean then to use component annotation. It will scan during the project start up and will create the bean if the component class exist in the component scan package.

        @Bean annotation is used to create a bean, this can use along with Configuration annotation. Bean annotation is a method level annotation and name of the method serves as a bean name. Component annotation is a class level annotation.

Difference between @Bean and @Component

Example:-

@Component
public class ProductUtil{

   //methods


}

@Bean annotation

@Configuration
class HMSAppConfiguration{

   @Bean
   public Customer getCustomer(){
      return new Customer();
   }
}

Youtube Video:- 

Thank you for reading the blog.