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.

Saturday, 30 September 2023

Difference between PermGen(Permanent Generation) and Metaspace in Java

        In this post, we will discuss the difference between PermGen i.e Permanent Generation and Metaspace in java 8(feature).

        Before java 8, static methods and variables are stored in PermGen space but in java 8 they have introduced new memory space called Metaspace. The default allocation size of PermGen is 64MB, if it exceeds it should throw an OutOfMemoryError. As if we need to fix this issue need to increase the PermGen space using JVM parameter –XX:MaxPermSize.

       Metaspace memory space introduced in java 8 to resolve the above issue. Internally it will automatically increases the size when allocation memory size increases. No need to increase the memory size manually.

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 can discuss one of the important java interview questions i.e difference between equals() and == operator and sample examples.

equals and == operator in java

The equals() method compares the content of two objects but == opeator checks the objects references of two objects for equality.

Let me see few examples to check both equals and == 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

Youtube Video:-


Thank you for visiting blog.

Thursday, 7 September 2023

Sort List In Ascending & Descending Order Using Java 8 stream API

        In one of the previous post, listed all the java 8 stream coding questions and answers(blog post). Today's post we will discuss one of the important coding questions i.e to sort the list in ascending and descending order using java 8 stream api.

1) Sort the string of list object in ascending order using java 8 stream

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 the string of list object in descending order using java 8 stream

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 the custom(Employee class) java object of list in ascending or descending order using java 8 stream

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 Injection

         In this post, we will learn the difference between Resource, Autowired and Inject annotation. All these annotations are used to inject the bean dependencies. Resource and Inject annotations are defined in Java and Autowired annotation defined in 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 us discuss with example of each Annotation execution path,

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 above code, the @Resource annotation will work fine without any error but @Autowired and @Inject will fail and through an exception like below,

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

           The Resource annotation checks by field name and it found the bean definition using name i.e email and will create the bean object internally but other two annotations checks by qualifier i.e by bean name mentioned in the component and there is no bean name with invalid and throw an exception.

Below code should works for all three annotations without fail.
 
@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(Exp - 9 to 12 yrs) interview questions

       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 from the given a list using Java 8 Stream

       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

Related Posts:-

1) Publicis Sapient Java Technical Lead Interview questions

2) mobtexting company Java Technical Lead interview questions

Wednesday, 16 August 2023

Java 8 Optional Class with examples

          In java8 introduced new class called Optional, using optional we can handle NullPointerException without using any null check condition.( Refer - Java 8 featuresIt provided many methods and using those it will be helpful to write cleanable code.

         Using optional if variable value is null then using orElse method we can have a null functionality code inside it.

 Below are the methods available in 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:

Tuesday, 15 August 2023

Java program to find the Second largest number in an Array or List

     Given an unsorted array of an integers or a List, to write a Java program to find the second largest number or element from the Array or a List

1) Given input is an array of integers

import java.util.Arrays;

public class SecondLargest {

	public static void main(String[] args) {	
		SecondLargest secondLargest = new SecondLargest();
		int[] array = { 2, 8, 3, 4, 5, 7 };
		System.out.println("Second largest number - " + secondLargest.findSecondLargestNumber(array));
	}

	private int findSecondLargestNumber(int[] array) {
		Arrays.sort(array);
		return array[array.length - 2];
	}

}

Output :- Second largest number - 7


2) Given input is a list

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

public class SecondLargest {

	public static void main(String[] args) {

		SecondLargest secondLargest = new SecondLargest();
		List<Integer> list = Arrays.asList(new Integer[] { 2, 8, 3, 4, 5, 7 });
		System.out.println("Second largest number - " 
					+ secondLargest.findSecondLargestNumber(list));
	}

	private int findSecondLargestNumber(List<Integer> listOfIntegers) {
		Collections.sort(listOfIntegers);
		return listOfIntegers.get(listOfIntegers.size() - 2);
	}

}

Output:- Second largest number - 7

3) Given input as a List, find second largest number using Stream(Java8)

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

public class SecondLargest {

	public static void main(String[] args) {

		SecondLargest secondLargest = new SecondLargest();
		List<Integer> list = Arrays.asList(new Integer[] { 2, 8, 3, 4, 5, 7 });
		System.out.println("Second largest number - " 
					+ secondLargest.findSecondLargestNumber(list));
	}

	private int findSecondLargestNumber(List<Integer> listOfIntegers) {
		return listOfIntegers.stream().sorted()
				.skip(listOfIntegers.size() - 2)
				.findFirst()
				.get();
	}

}

Output:- Second largest number - 7.


Thank you for visiting the blog.

Related page:-