0% found this document useful (0 votes)
19 views

HIBERNATE

Uploaded by

akumar181092
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

HIBERNATE

Uploaded by

akumar181092
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

HIBERNATE

What is @Query used for? (example)


Answer: Spring Data API provides many ways to define SQL query which can
be executed and Query annotations one of them. The @Query is an
annotation that is used to execute both JPQL and native SQL queries.

10. Give an example of using @Query annotation with JPQL.


Answer: Here is an example of @Query annotation from Spring Data
Application which returns all active orders from the database:
@Query("SELECT order FROM Orders o WHERE o.Disabled= 0")
Collection<User> findAllActiveOrders();
and, here is another example, which returns matching employees from the
database

@Query("select e from Employee e where se.name = ?1")


List<Employee> getEmployees(String name);

Can you name the different types of entity mapping.


Answer: one-to-one mapping, one-to-many mapping, many-to-one mapping,
and many-to-many mapping.

Differentiate between findById() and getOne().


Answer: The findById() is available in CrudRepository while getOne() is
available in JpaRepository. The findById() returns null if record does not exist
while the getOne() will throw an exception called EntityNotFoundException

What are the differences between JpaRepository and CrudRepository?


Answer:

JpaRepository CrudRepository

It extends QueryByExampleExecutor and it extends Repository interface


PagingAndSortingRepository interface

The saveAll method of JpaRepository returns The saveAll method of CrudRepository


list returns Iterable

Provides additional methods like Provides methods to perform CRUD


deleteInBatch(), flush() and others operations

10. What methods of CrudRepository apply in performing CRUD operations?


Answer:

 existsById – used to check if an entity of a given id already exists in the database.


 findAll() – find all entity of particular type.
 save(S entity) – it is used to save a single entity at a time.
 findById – used to get entity by id.
 findAllById – returns al entities of given ids.
 deleteById – used to delete the entity basing on id.
 count() – it returns the given number of entities.
 deleteAll() – delete all entities.

24.

What does the @EnableJpaRepositories annotation do?


Answer: this annotation enables the automatic generation of JPA
repositories. Any class which implements CrudRepository interface
will generate a repository when this annotation is present.

13. What does the @Query annotation do? (answer)


Answer: The @Query annotation allows you to define a Spring Data
Repository method with custom SQL. With the use of @Query, you
can map Spring Data Repository methods to actual SQL statements.

What is the difference between FetchType.Eager and FetchType.Lazy?


Answer: FetchType attribute indicates how whether records will be
eagerly or lazily loaded from the database. When the records are
eagerly loaded, JPA returns these objects regardless of whether
they are accessed by the client or not. When records are lazily
loaded the actual objects are only retrieved when directly
accessed. This helps in saving memory and processing when
appropriate.

25.
26. Hibernate Session is thread safe?
Hibernate Session object is not thread safe, every thread should get it's
own session ins
28. What is difference between Hibernate Session get() and
load() method?
Hibernate session comes with different methods to load data from database.
get and load are most used methods, at first look they seems similar but
there are some differences between them.

1. get() loads the data as soon as it's called whereas load() returns a
proxy object and loads data only when it's actually required, so load() is
better because it support lazy loading.
2. Since load() throws exception when data is not found, we should use it
only when we know data exists.
3. We should use get() when we want to make sure data exists in the
database.

For clarification regarding the differences, please read [Hibernate get vs


load](/communit

What are the advantages of using Hibernate over JDBC?

Major advantages of using Hibernate over JDBC are:

1. Hibernate eliminates a lot of boiler-plate code that comes with JDBC API, the
code looks cleaner and readable.
2. This Java framework supports inheritance, associations, and collections. These
features are actually not present in JDBC.
3. HQL (Hibernate Query Language) is more object-oriented and close to Java. But
for JDBC, you need to write native SQL queries.
4. Hibernate implicitly provides transaction management whereas, in JDBC API,
you need to write code for transaction management using commit and rollback.
5. JDBC throws SQLException that is a checked exception, so you have to write a
lot of try-catch block code. Hibernate wraps JDBC exceptions and
throw JDBCException or HibernateException which are the unchecked
exceptions, so you don’t have to write code to handle it has built-in transaction
management which helps in removing the usage of try-catch blocks.

What are the different functionalities supported by Hibernate?

 Hibernate is an ORM tool.


 Hibernate uses Hibernate Query Language(HQL) which makes it database-
independent.
 It supports auto DDL operations.
 This Java framework also has an Auto Primary Key Generation support.
 Supports cache memory.
 Exception handling is not mandatory in the case of Hibernate.

What is HQL?

HQL is the acronym of Hibernate Query Language. It is an Object-Oriented Query


Language and is independent of the database.

How to achieve mapping in Hibernate?

Association mappings are one of the key features of Hibernate. It supports the same
associations as the relational database model. They are:

 One-to-One associations
 Many-to-One associations
 Many-to-Many associations

You can map each of them as a uni- or bidirectional association

Mention some important annotations used for Hibernate mapping?

Hibernate supports JPA annotations. Some of the major annotations are:

1. javax.persistence.Entity: This is used with model classes to specify they are


entity beans.
2. javax.persistence.Table: It is used with entity beans to define the corresponding
table name in the database.
3. javax.persistence.Access: Used to define the access type, field or property.
The default value is field and if you want Hibernate to use the getter/setter
methods then you need to set it to a property.
4. javax.persistence.Id: Defines the primary key in the entity bean.
5. javax.persistence.EmbeddedId: It defines a composite primary key in the entity
bean.
6. javax.persistence.Column: Helps in defining the column name in the database
table.
7. javax.persistence.GeneratedValue: It defines the strategy to be used for the
generation of the primary key. It is also used in conjunction
with javax.persistence.GenerationType enum.

How do you integrate Hibernate with Struts2 or Servlet web applications?


You can integrate any Struts application with Hibernate. There are no extra efforts
required.

1. Register a custom ServletContextListener.


2. In the ServletContextListener class, first, initialize the Hibernate Session, store it
in the servlet context.
3. Action class helps in getting the Hibernate Session from the servlet context, and
perform other Hibernate task as normal.

What is the benefit of Native SQL query support in Hibernate?

Hibernate provides an option to execute Native SQL queries through the use of
the SQLQuery object. For normal scenarios, it is however not the recommended
approach because you might lose other benefits like Association and Hibernate first-
level caching.

Native SQL Query comes handy when you want to execute database-specific queries
that are not supported by Hibernate API such query hints or the Connect keyword in
Oracle Database.

Difference between get() vs load() method in Hibernate?

This is one of the most frequently asked Hibernate Interview Questions. The key
difference between the get() and load() method is:

load(): It will throw an exception if an object with an ID passed to them is not found.
get(): Will return null.

load(): It can return proxy without hitting the database unless required.
get(): It always goes to the database.

So sometimes using load() can be faster than the get() method.

JPA
Explain what type of collections can be used in JPA?

Ans: Following are the various types of collections that can be used to store
multivalued entity associations and a collection of objects.

 List
 Set
 Map

Explain the persistence life cycle of an object?

Ans: In the persistence life cycle, the object lies in the following phases: –

 Transient – In this phase, the object will be in a transient state when a new
keyword is declared, and it does not contain any primary key in the database.
 Persistence – In this phase, the object is associated with the session, and it is
retrieved from the database. It remains in the persistence state when it
contains a row of the database and consists of an identifier value.
 Detached – hibernate session is closed when the object enters into a
detached state. The amends made to the detached objects is saved to the
database.

MOCKITO
Why do we need mocking?
Answer: There are a lot of use cases of mocking that aid in unit testing of the code under
isolation and make the test highly repeatable and predictable.
Mocking is generally required when :
a) The component under test has dependencies that are not yet implemented or the
implementation is in progress.
A good example can be a REST API endpoint which will be available later at some point in
time, but you have consumed it in the code via a dependency.

Now as the real implementation is still not available, you really know most of the time what
is the expected response of that API. Mocks allow you to test those kinds of integration.

b) Component updates the state in the system.


Example: DB calls – you would not want to update your DB with data that is just for testing
purposes. This might result in corrupting the data, moreover, the availability of DB is
another challenge when the test is executed.
Thus to avoid such behavior, DB calls could be mocked in the component under test. Hence
there is no direct coupling of DB and the component under test.
Difference between doReturn and thenReturn.
Answer: Mockito provides two different syntaxes for creating stubs like:
 doReturn and thenReturn
 doNothing (no thenNothing)
 doThrow and thenThrow
Both these methods setup stubs and can be used to create/setup stubs and could be used
interchangeably at times.

So how do both of these differ?


a) The thenReturn way of stubbing is a type-safe way of setting up stubs. What this
essentially means is that it does a compile-time check against the return types that you
want to stub too.
Let’s understand this with an example:
Assume a method getItemDetails on mockedItemService which returns an object of
type ItemSku. So with thenReturn, you will not be able to return anything other than of type
ItemSku but with doReturn, you can set up the stub to return anything and the test will fail
(or throw an exception) during execution.
// works
when(mockedItemService.getItemDetails(123)).thenReturn(new ItemSku());
// throws compile time exception
when(mockedItemService.getItemDetails(123)).thenReturn(expectedPrice);
// with doReturn, both the stub setup works as it’s not compile safe.

// here we are trying to return an object of type double which still works and does not throw
any compile time warning.

doReturn(expectedPrice).when(mockedItemService.getItemDetails(123));
doReturn(new ItemSku()).when(mockedItemService.getItemDetails(123));
b) Another important difference between these 2 ways to the stub is for Mocked objects,
apart from compile safety there is not much difference.
However for Spied objects, “thenReturn” kind of stub setup will not work, as it will result in
calling the real method before the stubbed response is return as the call and not on a Mock,
but on Spy which is wrapping a real object instance.

So suppose, there is a spy named spiedObject and it has a method testMethod which
returns an integer, then to setup a stub on this you will need to use doReturn instead
of thenReturn.
doReturn(10).when(spiedObject.testMethod());

Why can’t static methods be mocked using Mockito?


Answer: Static methods are associated with the class itself and not any particular instance
of the class. This means that all instances/objects of the class use the same instance of the
static method.
Static methods are more like procedural code and are mostly used in legacy systems in
general.
Mock libraries typically create mocks by dynamical instance creation at runtime, either
through interfaces or through inheritance and as the static method is not associated with
any particular instance it’s not possible for mocking frameworks (like mockito, easy mock,
etc) to mock Static methods.

Frameworks like PowerMock which do have support for static methods perform bytecode
manipulation at runtime in order to mock static methods.

JAVA
https://www.knowledgehut.com/interview-questions/java
https://www.knowledgehut.com/interview-questions/java-oops

What is ‘Garbage Collection’ used for in Java?

The purpose of this feature is to identify and discard the objects that are no longer needed by the
application to facilitate the resources to be reclaimed and reused.

What’s the difference between ‘method overloading’ and ‘method overriding’?

In a “method overloading” case, methods that are in the same class share the same name, yet
their parameters differ. This is concerned with extensions of the method’s behavior more than
anything else. Reversely, “method overriding” sub-classes have methods of the same name and
parameters. The aim here is to alter the already-existing method’s behavior.

What’s the output of this Java program?

public class Test


{
Test(int x, int y)
{
System.out.println("x = "+x+" y = "+y);
}
Test(int x, float y)
{
System.out.println("x = "+x+" y = "+y);
}
public static void main (String args[])
{
byte x = 30;
byte y = 65;
Test test = new Test(x,y);
}
}

The correct answer is this:

a = 30 b = 65

Is it possible to execute a program without the 'main() method'?

Pretty standard among Java interview questions and yes, it is possible to do that. One of the most
common ways to execute a program like that is by using a static block.

What is ‘Inheritance’?

The term is honestly almost self-explanatory - inheritance is when one object acquires the
properties and parameters of another one (of a different class). The above-discussed method
overriding uses this - the main idea of inheritance is that you can build new classes on already-
existing ones. There are five different types of inheritance, but Java only supports four (Multiple
inheritances aren't supported). Why aren't Multiple inheritances supported? There’s only one
specific reason - to simplify the program. This should be an important note to remember for your
Java interview questions.

Do you know how to differentiate abstract class from the interface?

 Abstract classes can have method implementations whereas interfaces cannot.


 A class can extend only one abstract class but it can be implemented into multiple
interfaces.
 You can run an abstract class if it has main () method but not an interface.

What are the differences between HashMap and Hashtable?


Answer. The differences between HashMap and Hashtable in Java are:
1. Hashtable is synchronized while HashMap is not synchronized. For the
same reason, HashMap works better in non-threaded applications,
because unsynchronized objects typically perform better than
synchronized ones.
2. Hashtable does not allow null keys or null values whereas HashMap allows
one null key and any number of null values.
3. One of the subclasses of HashMap is LinkedHashMap, so if we want a
predictable iteration order in the event, we can easily swap out the
HashMap for a LinkedHashMap. But, this would not be as easy using
Hashtable.

Why is the Char array preferred over String for storing passwords?
Answer. As we know that String is immutable in Java and stored in the String
pool. Once we create a String, it stays in the String pool until it is garbage
collected. So, even though we are done with the password it is still available in
memory for a longer duration. Therefore, there is no way to avoid it.
It is clearly a security risk because anyone having access to a memory dump
can find the password as clear text. Therefore, it is preferred to store the
password using the char array rather than String in Java.

Differentiate between ArrayList and LinkedList.

ArrayList LinkedList
Implements dynamic array internally to Implements doubly linked list internally to
store elements store elements
Manipulation of elements is slower Manipulation of elements is faster
Can act only as a List Can act as a List and a Queue
Effective for data storage and access Effective for data manipulation

Differentiate between Set and Map.

Set Map
Belongs to java.util package Belongs to java.util package
Extends the Collection interface Doesn’t extend the Collection interface
Duplicate keys are not allowed but
Duplicate values are not allowed
duplicate values are
Only one null key can be stored but
Only one null values can be stored
multiple null values are allowed
Doesn’t maintain any insertion order Doesn’t maintain any insertion order

JAVA 8

What is a Lambda Expression, and why use them?


It’s a function that can be referenced and shared as an object. Lambda
Expressions require less coding, provide a means of implementing the Java 8 functional
interface, and let users encapsulate one behavior unit to pass around to other code.

What is a functional interface?

A functional interface is an interface that contains just one abstract method.

Why are default methods needed in the interface?

Default methods let you add new functionality to your libraries’ interfaces and ensure
binary compatibility with older code written for the interfaces.

What is a stream, and how does it differ from a collection?

A stream is an iterator whose function is to accept a set of actions and apply them to
each of the elements it contains. A stream represents an object sequence from a
collection or other source that supports aggregate operations. Unlike collections,
iteration logic implements inside the stream.

Also, streams are inherently lazily loaded and processed, unlike collections.

What is a default method, and when does it get used?

The default method involves an implementation, and it is found in the interface. The
method adds new functionalities to an interface while preserving backward compatibility
with the classes that already implement the interface.

What is stream pipelining?

Stream pipelining is the process of chaining different operations together. Pipelining


accomplishes this function by dividing stream operations into two categories,
intermediate operations, and terminal operations. When each intermediate operation
runs, it returns an instance of the stream. Thus, a user can set up an arbitrary number
of intermediate operations to process data, thereby forming a processing pipeline.

At the end of the process, there must be a terminal operation to return a final value and
terminate the pipeline.
JAVA PRACTICAL

Top 50 Java Programming Interview Questions | DigitalOcean

Which of the following would the below Java coding snippet return as
its output?

class Super {

public int index = 1;

class App extends Super {

public App(int index) {

index = index;

public static void main(String args[]) {

App myApp = new App(10);

System.out.println(myApp.index);

A. 0
B. 10
C. 1
D. Compile time error
Check correct option.
Answer. C
Write a Java program to reverse an array of integer values.

import java.util.Arrays;
public class Exercise11 {
public static void main(String[] args){
int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456};
System.out.println("Original array : "+Arrays.toString(my_array1));
for(int i = 0; i < my_array1.length / 2; i++)
{
int temp = my_array1[i];
my_array1[i] = my_array1[my_array1.length - i - 1];
my_array1[my_array1.length - i - 1] = temp;
}
System.out.println("Reverse array : "+Arrays.toString(my_array1));
}

Write a Java program to find the second largest element in an


array.

import java.util.Arrays;

public class Main {

public static void main(String[] args) {

int[] my_array = {
10789, 2035, 1899, 1456, 2013,

1458, 2458, 1254, 1472, 2365,

1456, 2165, 1457, 2456};

System.out.println("Original numeric array : "+Arrays.toString(my_array));

Arrays.sort(my_array);

int index = my_array.length-1;

while(my_array[index]==my_array[my_array.length-1]){

index--;

System.out.println("Second largest value: " + my_array[index]);

How do you get the highest number that exists on a list?

Use the following code segment:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

IntSummaryStatistics stats = integers.stream().mapToInt((x) −> x).summaryStatistics();


System.out.println("Lowest number in List : " + stats.getMin());

JSP

What is a Servlet?

Answer. A servlet in Java is a class that extends the capabilities of servers that
host applications accessed using a request-response programming model.
Servlets can be used to respond to any type of request, but they commonly
extend the applications hosted by web servers.
A servlet handles requests, processes them, and replies back with a response.
For example, a servlet can take input from a user using an HTML form, trigger
queries to get the records from a database and create web pages dynamically.

The primary purpose of the Servlet is to define a robust mechanism to send


content to a client-defined by the Client/Server model. The most popular use
of servlets is for generating dynamic content on the Web and have native
support for HTTP.

How are the JSP requests handled?


Answer. When the JSP requests arrive, the browser first requests a page that
has a .jsp extension. Then, the webserver reads the request. The Web server
converts the JSP page into a servlet class using the JSP compiler. The JSP file
gets compiled only on the first request of the page, or if there is any change in
the JSP file. The generated servlet class is invoked to handle the browser’s
request. The Java servlet sends the response back to the client when the
execution of the request is over.

What are JSP actions?


Answer. JSP actions use constructs in XML syntax that are used to control the
behavior of the servlet engine. JSP actions are executed when there is a
request for a JSP page. We can insert JSP actions dynamically into a file. JSP
actions reuse JavaBeans components, forward the user to another page, and
generate HTML for the Java plugin.
Some of the available JSP actions are listed below:

 jsp:include: It includes a file when there is a request for a JSP page.


 jsp:useBean: It instantiates or finds a JavaBean.
 jsp:setProperty: It is used to set the property of a JavaBean.
 jsp:getProperty: It is used to get the property of a JavaBean.
 jsp:forward: It forwards the requester to a new page.
 jsp:plugin: It generates browser-specific code.

What is a cookie? Differentiate between session and cookie?


Answer. A cookie is a small piece of data that the Web server sends to the
browser. The browser stores the cookies for each Web server in a local file.
Cookies provide a reliable mechanism for websites to remember stateful
information or to record the browsing activity of users.
The differences between the session and a cookie are:

 The session should work irrespective of the settings on the client’s


browser. The client can choose to disable cookies. However, the sessions
still work because the client has no ability to disable them on the server-
side.
 The session and cookies are also different in the amount of information
they can store. The HTTP session can store any Java object, while a cookie
can only store String objects.

MICROSERVICES
https://www.knowledgehut.com/interview-questions/microservices

What is REST/RESTful and what are its uses?

Representational State Transfer (REST)/RESTful web services are an architectural


style to help computer systems communicate over the internet. This makes
microservices easier to understand and implement.

Microservices can be implemented with or without RESTful APIs, but it’s always easier
to build loosely coupled microservices using RESTful APIs.

What is Spring Cloud?

According to the official website of Spring Cloud, Spring Cloud provides tools for
developers to quickly build some of the common patterns in distributed systems (e.g.
configuration management, service discovery, circuit breakers, intelligent routing,
leadership election, distributed sessions, cluster state).
What problems are solved by Spring Cloud?

While developing distributed microservices with Spring Boot we face few issues which
are solved by Spring Cloud.

 The complexity associated with distributed systems – This includes network issues,
Latency overhead, Bandwidth issues, security issues.
 Ability to handle Service Discovery – Service discovery allows processes and
services in a cluster to find each other and communicate.
 Solved redundancy issues – Redundancy issues often occur in distributed systems.
 Load balancing – Improves the distribution of workloads across multiple computing
resources, such as a computer cluster, network links, central processing units.
 Reduces performance issues – Reduces performance issues due to various
operational overheads.

What is End to End Microservices Testing?

End-to-end testing validates each and every process in the workflow is functioning
properly. This ensures that the system works together as a whole and satisfies all
requirements.

In layman terms, you can say that end to end testing is a kind of tests where everything
is tested after a particular period.

What is the use of Container in Microservices?

Containers are a good way to manage microservice based application to develop and
deploy them individually. You can encapsulate your microservice in a container image
along with its dependencies, which then can be used to roll on-demand instances of
microservice without any additional efforts required.

What are the main components of Microservices?


Answer: The main components for a Microservice Architecture are:

 Containers, Clustering, and Orchestration


 IaC [Infrastructure as Code Conception]
 Cloud Infrastructure
 API Gateway
 Enterprise Service Bus
 Service Delivery
List the differences between Monolithic, SOA, and Microservices Architecture
with an example for each.
Answer:

In Monolithic Microservices Architecture is a collection of


SOA [Service Oriented
Architecture, all software small functional modules. These functional
Architecture] is a collection of
components of the modules are independently deployable,
services that communicate with
application are scalable, target specific business goals, and
each other through simple data
assembled and packed communicate with each other over standard
passing or activity coordination.
tightly. protocols.

How do you implement a Spring Security in a Spring Boot Application?


Answer:

 Add spring-boot-starter-security in the file pom.xml.


 Create a Spring config class that will override the required method while extending the
WebSecurityConfigurerAdapter to achieve security in the application.

What is Eureka in Microservices?


Answer: Eureka is alternatively known as the Netflix Service Discovery Server. It uses
Spring Cloud and is not heavy on the application development process.

Why are Container used in Microservices?


Containers are easiest and effective method to manage the microservice based
application. It also helps you to develop and deploy individually. Docker also
allows you to encapsulate your microservice in a container image along with its
dependencies. Microservice can use these elements without additional efforts.

What are the features of microservices?


Answer: Features are:
 Decoupling: Applications can be easily decoupled or rather separated to have
individual functionality, which implies it assures easy development, maintenance,
and deployment.
 Componentization: In componentization, every microservice is treated as an
individual component and it is responsible or manages all the intricacies as far as a
particular service is concerned. It focuses only on that. It is loosely coupled with
other services. That is why each of them can be thought of as a single component or
a container.
 Business capabilities: We can focus business capabilities much better way since
you are setting up smaller goals and you focus on individual functionalities. It
becomes easier to develop applications to meet these requirements as far as your
business is concerned.
 Autonomy: The developers are now free because, as a result of small team
clusters, they’re free to develop the applications. This implies that the other teams
and developers are not interdependent on each other. This assures speeded
allotment of software.
 Continuous delivery: Since you have so many features which we just discussed,
this ensures that you have constant and frequent releases of software, and a system
can be continuously updated and modified in alignment with the needs of a particular
company or a particular business domain.
 Responsibility: In this approach, every domain or every project is treated as a
product. This means that a team will take responsibility for the so-called product and
they will bring it to life, and it is that responsibility, i.e. builds it, test it and carry on
with the whole lifecycle.
 Agility: Since you have a decentralized architecture, you can easily build
applications and discard them if they’re no longer needed.

How to implement Service discovery and Api gateway for your


microservices ?

SPRINGBOOT
https://www.knowledgehut.com/interview-questions/spring
https://www.knowledgehut.com/interview-questions/spring-boot

What Are the Differences Between Spring and Spring


Boot?
The Spring Framework provides multiple features that make the development
of web applications easier. These features include dependency injection, data
binding, aspect-oriented programming, data access and many more.
Over the years, Spring has been growing more and more complex, and the
amount of configuration such application requires can be intimidating. This is
where Spring Boot comes in handy — it makes configuring a Spring
application a breeze.
Essentially, while Spring is unopinionated, Spring Boot takes an
opinionated view of the platform and libraries, letting us get started
quickly.
Here are two of the most important benefits Spring Boot brings in:

 Auto-configure applications based on the artifacts it finds on the


classpath
 Provide non-functional features common to applications in production,
such as security or health checks

Please check out our other tutorial for a detailed comparison between vanilla
Spring and Spring Boot.

What do we mean by an IOC container?


Ans: Yet another very common Spring Boot interview questions for 10 years
experience is the meaning of IOC container. Well, IOC container refers to the
framework which is responsible for the implementation of automatic
dependency injection. It serves quite a few purposes, such as injecting
dependencies into a class and managing object creation and its lifeline.
Whenever you need to create an object of a specified class, an IOC container
is used. Furthermore, it is also responsible for injecting all the dependency
objects during run time and disposing of the same at the appropriate time.
Thus, you no longer need to create or manage objects manually.

How are the @RestController and @Controller Annotation different?

The traditional Spring @Controller annotation specifies that an annotated class


represents a controller. It’s basically a @Component specialization, and it is
autodetected via the classpath scanning. The @Controller annotation is used along with
the annotated handler methodologies based on @RequestMapping annotations.

Developers use the @RestController annotation to develop RESTful web services,


utilizing the Spring Model–View–Controller (MVC). The Spring @RestController maps
the request data to specified request handler methods. Once the handler method
generates the response body, the @RestController modifies it to XML or JSON
response

How to Disable a Specific Auto-Configuration?


If we want to disable a specific auto-configuration, we can indicate it using
the exclude attribute of the @EnableAutoConfiguration annotation.
For instance, this code snippet neutralizes DataSourceAutoConfiguration:
// other annotations
@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
public class MyConfiguration { }

What Is Spring Boot Actuator Used For?


Essentially, Actuator brings Spring Boot applications to life by enabling
production-ready features. These features allow us to monitor and manage
applications when they're running in production.
Integrating Spring Boot Actuator into a project is very simple. All we need to
do is include the spring-boot-starter-actuator starter in the pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>Copy
Spring Boot Actuator can expose operational information using either HTTP or
JMX endpoints. But most applications go for HTTP, where the identity of an
endpoint and the /actuator prefix form a URL path.
Here are some of the most common built-in endpoints Actuator provides:

 env exposes environment properties


 health shows application health information
 httptrace displays HTTP trace information
 info displays arbitrary application information
 metrics shows metrics information
 loggers shows and modifies the configuration of loggers in the
application
 mappings displays a list of all @RequestMapping paths

Which Is Better to Configure a Spring Boot Project —


Properties or YAML?
YAML offers many advantages over properties files:

 More clarity and better readability


 Perfect for hierarchical configuration data, which is also represented in a
better, more readable format
 Support for maps, lists and scalar types
 Can include several profiles in the same file (since Spring Boot 2.4.0,
this is possible for properties files too)

However, writing it can be a little difficult and error-prone due to its indentation
rules.

What Basic Annotations Does Spring Boot Offer?


The primary annotations that Spring Boot offers reside in
its org.springframework.boot.autoconfigure and its sub-packages.
Here are a couple of basic ones:

 @EnableAutoConfiguration – to make Spring Boot look for auto-


configuration beans on its classpath and automatically apply them
 @SpringBootApplication – to denote the main class of a Boot
Application. This annotation
combines @Configuration, @EnableAutoConfiguration and @Compone
ntScan annotations with their default attributes.

APACHE KAFKA
https://www.knowledgehut.com/interview-questions/kafka

How is Kafka messaging system different than other messaging


frameworks?
The answer to such Kafka interview questions should be straightforward. Candidates can outline
their response in the form of bullet points that differentiate Kafka from other messaging or real-time
data streaming platforms. Here are the pointers that separate Kafka from the rest of its competition.

 The design follows a public-subscribe model.


 Seamless support for Spark and other Big Data technologies.
 Support for cluster mode operation.
 Fault tolerance capability for reducing concerns of message loss.
 Support for Scala and Java programming languages.
 Ease of coding and configuration.
 Ideal for web service architecture as well as big data architecture.

Do You know the different components of Kafka?


This is a frequently asked Kafka interview question for which candidates should prepare well. Kafka
has four major components, such as Topic, Producer, Brokers, and Consumers. The topic in Kafka is
a stream of messages that are of the same type.

The Producer in Kafka helps in publishing messages to a topic. Brokers are the set of servers that
store the published messages by producers. Consumers are the Kafka component, which helps in
subscribing to different topics and pulling data from the brokers.

Define a consumer group in Kafka?


Candidates can face such entries among the most common Kafka interview questions. First of all, it
is essential to note that Consumer Groups is a concept exclusively specific for Apache Kafka. Each
consumer group in Kafka comprises of one or more consumers consuming an assortment of
subscribed topics, in collaboration.

Can I use Kafka without Zookeeper?


No. You cannot bypass Zookeeper for a direct connection with the Kafka server. In addition, it is
also essential to note that servicing client requests becomes impossible when Zookeeper is
experiencing downtime.

What are some of the unique features of Kafka Stream?


Kafka Stream is the ideal real-time data streaming tool for different reasons. Here are the unique
features that establish the popularity of Kafka Stream.

 High scalability and fault tolerance.


 Easy deployment to the cloud, containers, bare metal or virtual machines.
 Through integration with Kafka security.
 Facility for writing standard Java applications.
 One-time processing semantics.
 Suitable for the small, medium as well as large use cases.
 No requirement of separate processing clusters.

What is the importance of Replicas in Kafka?


Replicas in Kafka are basically a list of nodes that replicate the log for a specific partition without
considering whether the nodes serve as the Leader. Replicas are highly significant in Kafka because
of the safety of published messages. Replication ensures that users can consume published messages
even in circumstances such as program error, regular software updates, or machine errors.

How is Apache Kafka better than RabbitMQ?


Candidates could also expect such the latest Kafka interview questions. RabbitMQ is the most
notable alternative for Apache Kafka. The features of Kafka as a distributed, highly available, and a
durable system for data sharing and replication are better than RabbitMQ, which does not have these
features. The performance rate of Apache Kafka could extend up to 100,000 messages per second.
On the other hand, RabbitMQ has a limited performance rate of around 20,000 messages per second.

Is getting message offset possible after producing?

This is not possible from a class behaving as a producer because, like in most queue
systems, its role is to forget and fire the messages. As a message consumer, you get
the offset from a Kaka broker.

What maximum message size can the Kafka server receive?

The maximum message size that Kafka server can receive is 10 lakh bytes.

What is Kafka producer Acknowledgement?

An acknowledgement or ack is sent to the producer by a broker to acknowledge receipt


of the message. Ack level defines the number of acknowledgements that the producer
requires before considering a request complete.
How do you start a Kafka Server?
Ans. Before you start the Kafka Server, you need to start the ZooKeeper. First, you should
download the new version of KafkaYou need to enter a command in the terminal to start the
ZooKeeper a. Once it starts running, you can start the Kafka Server.

What are the different ways that Kafka imposes security?


Ans. The following are the different ways through which Kafka imposes security.:-

 Encryption
 Authentication
 Authorization

Encryption - The communications between the Kafka broker and its clients are highly encrypted,
which secures data from the interruptions of other clients. Further, messages are also shareable with
proper encryption between the components.
Authentication - Applications that use Kafka brokers need authentication before they connect with
Kafka. Only approved apps can send or receive messages in this case. These authorized apps will
include a unique ID and password to locate themselves quickly.
Authorization - The authorization process executes after the authentication process. After its
validation, a client can publish or consume messages. The permission limits the app's writing access
to prevent data impurity.

You might also like