Tuesday, 24 October 2023

How to Return DTOs from Native Queries in Spring Data JPA

         In this post, we will discuss how to return DTOs from a JPA repository method using the results of a native query without relying on entity mapping.

     JPA provides many built-in repository methods, such as findAll(), findById(), and others, for performing database operations. These methods map the query results to the corresponding entity classes.

However, in some scenarios, we need to use native SQL queries to join multiple tables and retrieve only the required data. In such cases, there may not be a suitable entity that matches the query result, making direct entity mapping impractical. Instead, we can map the native query result directly to a DTO.

This can be achieved using an interface-based DTO projection. With this approach, the JPA repository maps the native query result directly to a DTO projection, eliminating the need to first map the result to an entity and then manually convert the entity into a DTO.

Let's understand this with the following example.

JPA repository with a 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();
}

Create a ReportDto interface with getter methods corresponding to the fields returned by the native query. In this example, the native query selects three fields: zoneName, propertyType, and amountCollected.

The interface-based DTO is shown below:


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 Annotations in Spring

          As discussed in one of our previous blog posts on Spring stereotype annotations, @Component is a stereotype annotation in the Spring Framework. It is used to mark a Java class as a Spring-managed bean. During application startup, Spring scans the packages configured for component scanning, detects classes annotated with @Component, and automatically registers them as beans in the Spring container.

The @Bean annotation is used to explicitly define a bean in the Spring container. It is a method-level annotation and is typically used within a class annotated with @Configuration. The name of the @Bean method is used as the bean name by default, although it can be customized.

In summary, @Component is a class-level annotation used for automatic bean detection through component scanning, whereas @Bean is a method-level annotation used for explicit bean creation and configuration.

Difference between @Bean and @Component

Example:-

@Component
public class ProductUtil{

   //methods


}

@Bean annotation

@Configuration
class HMSAppConfiguration{

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


Thank you for reading the blog.

Saturday, 30 September 2023

Difference Between PermGen (Permanent Generation) and Metaspace in Java

        In this post, we will discuss the differences between PermGen (Permanent Generation) and Metaspace in Java.

Before Java 8, class metadata was stored in the PermGen (Permanent Generation) memory space. If the allocated PermGen space was exhausted, the JVM threw an OutOfMemoryError. By default, the PermGen size was limited, and if required, it could be increased using JVM options such as -XX:MaxPermSize.

Java 8 removed PermGen and introduced Metaspace to address these limitations. Unlike PermGen, Metaspace stores class metadata in native memory rather than in the JVM heap. By default, Metaspace automatically expands as needed (subject to the available native memory), eliminating the need to manually increase its size in most cases. If required, its maximum size can still be limited using the -XX:MaxMetaspaceSize JVM option.

PermGen and Metaspace difference

Thank you for visiting the blog.

Wednesday, 27 September 2023

Difference Between equals() Method and == Operator in Java

     In this post, we will discuss one of the most common Java interview questions: the difference between the equals() method and the == operator. We will also explore practical examples to understand when and how each should be used.

equals and == operator in java

The equals() method compares the contents (or logical equality) of two objects, whereas the == operator compares their object references to determine whether both references point to the same object in memory.

Let's look at a few examples to understand the difference between the equals() method and the == operator.

  • Created two string objects using new operator and applied equals and == operator to check the equality.
public class DemoClass {

     public static void main(String[] args) {

	  String s1 = new String("A");
	  String s2 = new String("A");

	  if (s1.equals(s2)) {
		System.out.println("s1 equals s2 are equal");
	  } else {
		System.out.println("s1 equals s2 are not equal");
	  }

	  if (s1 == s2) {
	       System.out.println("s1 == s2 are equal");
	  } else {
	       System.out.println("s1 == s2 are not equal");
	  }

      }
}

Output:- 
s1 equals s2 are equal
s1 == s2 are not equal

Used new operator to create String objects and those objects will store in heap memory of JVM and will create two different objects in the heap even the contents are same. So == operator result will return false.
  • Created two string objects using literal and applied equals and == operator to check the equality.
public class DemoClass {

     public static void main(String[] args) {

	  String s1 = "A";
	  String s2 = "A";

	  if (s1.equals(s2)) {
		System.out.println("s1 equals s2 are equal");
	  } else {
		System.out.println("s1 equals s2 are not equal");
	  }

	  if (s1 == s2) {
	       System.out.println("s1 == s2 are equal");
	  } else {
	       System.out.println("s1 == s2 are not equal");
	  }

      }
}

Output:-

s1 equals s2 are equal
s1 == s2 are equal

Thank you for visiting blog.

Thursday, 7 September 2023

Sort a List in Ascending and Descending Order Using the Java 8 Stream API

        In one of my previous posts, I covered several Java 8 Stream API coding questions and answers. In this post, we will discuss one of the most commonly asked coding interview questions: how to sort a list in ascending and descending order using the Java 8 Stream API.

1) Sort a List of Strings in Ascending Order Using the Java 8 Stream API

import java.util.Arrays;
import java.util.List;

public class SortExample {

    public static void main(String[] args) {

	 List<String> listOfStrings = Arrays.asList("A", "E", "B", "C");

         listOfStrings.stream().sorted().forEach(s -> System.out.println(s));
    }

}

Output:- A
              B
              C
              E

2) Sort a List of Strings in Descending Order Using the Java 8 Stream API

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class SortExample {

     public static void main(String[] args) {

	  List<String> listOfStrings = Arrays.asList("A", "E", "B", "C");

          listOfStrings.stream().sorted(Comparator.reverseOrder())
                                              .forEach(s -> System.out.println(s));
     }

}

Output:-   E
                C
                B
                A

3) Sort a List of Custom Java Objects (Employee Class) in Ascending or Descending Order Using the Java 8 Stream API

Employee.java,
public class Employee {
	
	private Long id;
	private String firstName;
	private String lastName;
	private String address;
      
        //constructor, setter and getter
       // and toString metghod
}

SortExample.java,
package com.main;

import java.util.ArrayList;
import java.util.List;

public class SortExample {

     public static void main(String[] args) {
		
	 Employee e1 = new Employee(1L, "Anil", "Nivargi", "XYZ");
	 Employee e2 = new Employee(2L, "Mahesh", "Nivargi", "XYZ");

	 List<Employee> employeeList = new ArrayList<>();
	 employeeList.add(e1);
	 employeeList.add(e2);
		
	  System.out.println("Sort a list in ascending order using firstName -");
		
	  //sort a list in ascending order using firstName
	  employeeList.stream().sorted((s1,s2) -> 
                        s1.getFirstName().compareTo(s2.getFirstName())).forEach(
                                 s -> System.out.println(s));
		
	  System.out.println("Sort a list in descending order using firstName -");
		
	    //sort a list in descending order using firstName
	  employeeList.stream().sorted((s1,s2) -> 
                        s2.getFirstName().compareTo(s1.getFirstName())).forEach(
                                 s -> System.out.println(s));

     }

}

Output:- 
Sort a list in ascending order using firstName -
Employee [id=1, firstName=Anil, lastName=Nivargi, address=XYZ]
Employee [id=2, firstName=Mahesh, lastName=Nivargi, address=XYZ]
Sort a list in descending order using firstName -
Employee [id=2, firstName=Mahesh, lastName=Nivargi, address=XYZ]
Employee [id=1, firstName=Anil, lastName=Nivargi, address=XYZ]

Thank you reading the blog post.

Reference Posts:-

Friday, 1 September 2023

Difference Between @Resource, @Autowired, and @Inject in Spring

         In this post, we will learn the differences between the @Resource, @Autowired, and @Inject annotations. All three annotations are used for dependency injection in Spring applications. The @Resource and @Inject annotations are part of the Java specification, whereas the @Autowired annotation is provided by the Spring Framework.

@Resource – It's defined in the javax.annotation package and it's part of java.

@Inject – It's defined in the javax.inject package and it's part of Java

@Autowired – It's defined in the package org.springframework.bean.factory and part of Spring framework.

          Internally @Inject and @Autowired annotations use the AutowiredAnnotationBeanPostProcessor to inject the dependencies. But @Resource annotation internally use CommonAnnotationBeanPostProcessor to inject the dependencies. Execution path/step is same for both Inject and Autowired annotations, Resource annotation execution paths also same but order of execution paths are not same.

  • @Inject and @Autowired
         1) Matches by Type
         2) Restricts by Qualifiers
         3) Matches by Name
  • @Resource
         1) Matches by Name
         2) Matched by Type
         3) Restricts by Qualifiers

Let's discuss the execution flow of each annotation with an example.

Notification.java,
public interface Notification {
    // some methods
}

Email.java,
import org.springframework.stereotype.Component;
@Component
public class Email implements Notification {
    // some methods
}

SMS.java,
import org.springframework.stereotype.Component;
@Component
public class SMS implements Notification {
    // some methods
}

Inject the above beans into the caller java class,

@Resource
@Qualifier("invalid")
private Notification email;
 
@Autowired
@Qualifier("invalid")
private Notification email;
 
@Inject
@Qualifier("invalid")
private Notification email;

When we execute the above code, the @Resource annotation works without any errors. However, the @Autowired and @Inject annotations fail and throw an exception, as shown below.

org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.prj.basics.notification.Notification]

           The @Resource annotation performs dependency injection by matching the field name. In this example, it finds the bean named email and injects it successfully. However, the @Autowired and @Inject annotations resolve dependencies by type first and then use the qualifier (bean name) if one is specified. Since no bean named invalid exists, both annotations fail and throw an exception.

The following code works correctly for all three annotations without any errors.

@Resource
@Qualifier("email")
private Notification email;
 
@Autowired
@Qualifier("email")
private Notification email;
 
@Inject
@Qualifier("email")
private Notification email;

OR 

@Resource
private Email email;
 
@Autowired
private Email email;
 
@Inject
private Email email;

Thank you for visiting the blog.

Reference posts:-

Tuesday, 29 August 2023

Akkodis Company Java Technical Lead Interview Questions (9–12 Years Experience)

       Below are the list of java technical lead interview questions asked in Akkodis during the firstround.

1) What are the features in java8 ?

2) Why introduced default method in java 8 ?

3) What is the use of static method in java 8 ?

4) What is functional interface in java8 ?

5) What is the use of flatMap in streams and explain with example

6) List<Integer> list = Arrays.asList(10, 23, 8, null);

Write a program to sort the list in ascending and descending order and remove the nulls --using streams

7) what is generics in java ? Is this supports polymorphism ? (Answer -- yes)
if yes then which polymorphism supports compile or runtime(Answer - runtime)  

8) How many ways to create thread ? which one prefer and why ?

9) What implemenation or changes done in HashMap in java 8 ?

10) Which scenario's to use ArrayList and LinkedList

11) Asked some Linux commands.

12) Explain contract between equals and hashcode method.

13) What are the intermediate functions in streams.

14) How to make ArrayList as final - as final is immutable.

15) How to create singleton object and how to restrict for clone and deserialization

16) How to handle global the exception in spring boot

17) What is checked and unchecked exception

18) How to set the priority thread in threads.

19) What is completable future in java 8.


Thank you for visiting the blog.

Thursday, 24 August 2023

Find Duplicate Elements in a List Using the Java 8 Stream API

       In this post, we need to have a look one of the important coding interview questions asked for java 8 streams. Given list contains either String or Integers. Refer all coding questions here

1) Print duplicate elements using frequency and toSet methods    . 

      In the below code used Collections.frequency to filter the data with occurance value greater than 1 and toSet method used to remove the duplicated in output.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Java8StreamEx {

    public static void main(String[] args) {

	 List<Integer> integerList = Arrays.asList(2, 3, 3, 5, 6, 6, 6);

	 Set<Integer> list = integerList.stream().filter(
			        s -> Collections.frequency(integerList, s) > 1)
                                  .collect(Collectors.toSet());
		
	 list.stream().forEach(s -> System.out.println("Duplicate element - "+s));
     }
}

Output:- Duplicate element - 3
              Duplicate element - 6

2) Using frequency and toMap method(map used to store element with occurance)

Used frequency and toMap method to store duplicates into the Map with occurance as a value.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Java8StreamEx {

    public static void main(String[] args) {

	 List<Integer> integerList = Arrays.asList(2, 3, 3, 5, 6, 6, 6);

		// store duplicate into the map
	  Map<Integer, Long> map = 
                         integerList.stream().filter(
	                    s -> Collections.frequency(integerList, s) > 1).collect(
			    Collectors.toMap(Function.identity(), v -> 1L, Long::sum));

		map.entrySet().stream().forEach(s -> System.out.println(s));
	}
}

Output: - 3=2
               6=3

3) Using groupingBy and counting methods - group the similar elements and to find the occarance used counting.

To write the code to find the duplicate using groupingBy,

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Java8StreamEx {

     public static void main(String[] args) {

          List<String> listOfString = Arrays.asList("A", "B", "C", "A", "A", "D", "B");

	  Map<String, Long> mapOfStrings = 
			listOfString.stream().filter(
			    s -> Collections.frequency(listOfString, s) > 1)
			    .collect(Collectors.groupingBy(Function.identity(), 
			        Collectors.counting()));

	   mapOfStrings.entrySet().stream().forEach(s -> System.out.println(s));
    }
}

Output:-A=3
             B=2


Thank you for visiting blog.

Refer the post for coding questions - coding questions

Monday, 21 August 2023

LTIMindtree Java technical Lead interview questions

       Below are the list of java technical lead interview questions asked in LTIMindtree during the first round.

1) Explain Saga design pattern used in Microservice(Answer)

2) What is orchestrator in Saga pattern?(Answer)

3) Which authentication mechanism used in project and how to implemented(AOuth2 with bearer token)?

3) What is the use of Eureka server?(Answer)

4) What is Functional interface in java 8? do we have default method in Functional interface(Answer)

5) Why introduced deafult method in interface in java 8?(Answer)

6) What is lambda expression ?(Answer)

7) What is difference between collection and stream?(Answer)

8) What is the use of status code in Rest API ?(Answer)

9) What is database/memory lock expeption?

10) What are HTTP idempotent methods?(Answer)

11) What are the key components in spring boot?

12) What is the use of @WebMvcTest . Difference between @WebMvcTest and @SpringBootTest(Answer)

13) Write a program to find second largest word in the sentence.

14) Write a query to find the max salary from the employee table whose name is Reta


Thank you for visiting blog.

Previous                                                   Home

Wednesday, 16 August 2023

Java 8 Optional Class with Examples

         Java 8 introduced a new class called Optional, which helps handle NullPointerException without requiring explicit null checks. (Refer to: Java 8 Features.) It provides several utility methods that make the code more readable, maintainable, and cleaner.

When a value is null, you can use methods such as orElse() to provide a default value or execute alternative logic.

Below are some of the commonly used methods available in the Optional class:

Java 8 optional class methods

The Optional.ofNullable() --- > method returns a Non-empty Optional if a value present in the given object. Otherwise returns an empty Optional. 

Optional.empty() -- > method is useful to create an empty Optional object.

Optional.of(value) --> creates an Optional object using value. 

Optional.ifPresent -- > If optional variable value is present, invoke the specified consumer with the value, otherwise, do nothing.

orElse --> If optional variable value is null then invokes orElse method.

 orElseGet --> If optional variable value is null then invokes orElse method and return the result of that invocation.

 orElseThrow --> If optional variable value is null then invokes orElseThrow method and throws the exception provided in the method.

 get -- > method returns the value from the optional.

 isPresent - if optional variable value is present/exist then return true else it's false.


Optional Class Code Example - 

import java.util.Optional;

public class OptionalClassUsages {
	
	public static void main(String[] args) {
		
		//ofNullable, orElse, orElseGet and orElseThrow method example
		String str = "Optional with ofNullable method usage";
		System.out.println(Optional.ofNullable(str).orElse("null logic"));
		
		str = null;
		System.out.println(Optional.ofNullable(str).orElse("null logic"));
		System.out.println(Optional.ofNullable(str).orElseGet(() -> "orElseGet method"));
		
		try {
			Optional.ofNullable(str).orElseThrow(() -> {
				return new Exception("orElseThrow Exception");
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//optional of, ifPresent, filter usages
		Optional<String> optional = Optional.of("ab");
		optional.ifPresent(s-> System.out.println(s));
		optional.filter(s->s.equals("ab"))
				.ifPresent(s-> System.out.println("ifPresent method usage"));
		
		//isPresent and get method usage example
		System.out.println(optional.isPresent());
		System.out.println(optional.get());	
	}
}

Output:- 

Optional with ofNullable method usage
null logic
orElseGet method
java.lang.Exception: orElseThrow Exception
	at com.main.OptionalClassUsages.lambda$1(OptionalClassUsages.java:19)
	at java.util.Optional.orElseThrow(Optional.java:290)
	at com.main.OptionalClassUsages.main(OptionalClassUsages.java:18)
ab
ifPresent method usage
true
ab


Thank you for visiting the blog.

Previous                                                    Home                                                                            Next

Reference posts: