HIBERNATE
HIBERNATE
JpaRepository CrudRepository
24.
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.
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 is HQL?
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
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.
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.
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
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.
// 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());
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
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.
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.
a = 30 b = 65
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.
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.
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
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
Default methods let you add new functionality to your libraries’ interfaces and ensure
binary compatibility with older code written for the interfaces.
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.
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.
At the end of the process, there must be a terminal operation to return a final value and
terminate the pipeline.
JAVA PRACTICAL
Which of the following would the below Java coding snippet return as
its output?
class Super {
index = index;
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));
}
import java.util.Arrays;
int[] my_array = {
10789, 2035, 1899, 1456, 2013,
Arrays.sort(my_array);
while(my_array[index]==my_array[my_array.length-1]){
index--;
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.
MICROSERVICES
https://www.knowledgehut.com/interview-questions/microservices
Microservices can be implemented with or without RESTful APIs, but it’s always easier
to build loosely coupled microservices using RESTful APIs.
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.
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.
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.
SPRINGBOOT
https://www.knowledgehut.com/interview-questions/spring
https://www.knowledgehut.com/interview-questions/spring-boot
Please check out our other tutorial for a detailed comparison between vanilla
Spring and Spring Boot.
However, writing it can be a little difficult and error-prone due to its indentation
rules.
APACHE KAFKA
https://www.knowledgehut.com/interview-questions/kafka
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.
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.
The maximum message size that Kafka server can receive is 10 lakh bytes.
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.