Corejava Interview Booster 9
Corejava Interview Booster 9
=================================
In your code, you are currently using a `Predicate<Student>` to filter students
based on marks (`marks >= 60`). You want to extend this by using `Predicate` in the
if-else conditions.
Here’s an approach to modify your existing code so that each condition in your if-
else block is replaced by a `Predicate`:
### Steps:
1. **Create multiple predicates**: Each predicate will represent a condition, like
`marks >= 80`, `marks >= 60`, etc.
2. **Use `Predicate` for grading**: Each predicate will test the condition, and
based on that, you can assign the appropriate grade.
```java
import java.util.function.*;
class Student {
String name;
int marks;
class Test {
public static void main(String[] args) {
Student[] students = {
new Student("Durga", 100),
new Student("Sunny", 65),
new Student("Bunny", 55),
new Student("Chinny", 45),
new Student("Vinny", 25)
};
for (Student s : students) {
if (passCondition.test(s)) {
System.out.println("Student Name: " + s.name);
System.out.println("Student Marks: " + s.marks);
System.out.println("Student Grade: " + f.apply(s));
System.out.println();
}
}
}
}
```
### Explanation:
- **Predicates**:
- `distinction`, `firstClass`, `secondClass`, `thirdClass`, and `failed` are
all predicates that test whether the student's marks fall within a specific range.
- **Function `f`**:
- The `Function<Student, String>` now uses these predicates to assign the
appropriate grade.
- **`passCondition`**:
- This predicate checks if the student has passed (`marks >= 60`) before
printing their details.
This approach modularizes the logic using predicates, making your code more
readable and functional. Let me know if you'd like further adjustments!
========================
In Java, **non-primitive data types** (also known as **reference types**) refer to
objects that are instances of classes. Unlike primitive data types (like `int`,
`char`, `boolean`), non-primitive data types store references to memory locations
where the actual objects are stored.
### 1. **Strings**
- **Description**: A `String` is a sequence of characters.
- **Example**:
```java
String name = "Java";
```
### 2. **Arrays**
- **Description**: Arrays are collections of elements of the same type.
- **Example**:
```java
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
```
### 4. **Interfaces**
- **Description**: Interfaces are abstract types used to specify behavior that
classes must implement.
- **Example**:
```java
interface Vehicle {
void start();
}
### 6. **Enums**
- **Description**: Enums are special classes that represent a fixed set of
constants.
- **Example**:
```java
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
}
These non-primitive types allow for more complex data structures and operations in
Java, providing much greater flexibility compared to primitive types.
==============================
A **functional interface** in Java is an interface that contains exactly one
abstract method. It is important for several reasons, especially when working with
lambda expressions and functional programming in Java.
Example:
```java
// Without Lambda Expression
Runnable r = new Runnable() {
public void run() {
System.out.println("Running without Lambda");
}
};
2. **Simplify Code:**
Functional interfaces, combined with lambda expressions, reduce boilerplate
code. Instead of writing multiple lines to define an anonymous class for a single
method interface, you can use a lambda expression, making the code more readable
and maintainable.
Example:
```java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
```
```java
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
list.forEach(System.out::println);
```
```java
list.forEach(s -> System.out.println(s)); // This can be replaced by
list.forEach(System.out::println);
```
### 3. **In Event Handling (Functional Interfaces)**
You can use method references like `System.out::println` in event-driven
programming or with any functional interface that accepts a single argument:
```java
Runnable r = System.out::println;
r.run("Hello, World!"); // Prints "Hello, World!"
```
### Relationships
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "password")
private String password;
@Version
private int version;
In this example:
- The `User` class is an entity mapped to the `users` table.
- The `id` field is the primary key and will be auto-generated.
- The `username` field is mapped to a column that cannot be null and must be
unique.
- The `version` field is used for optimistic locking.
These annotations provide a powerful way to define the structure of your database
in a way that is tightly integrated with your Java code.
=============================
In Hibernate, the `@GeneratedValue` annotation is used to specify how the primary
key value is generated for an entity. There are several strategies for generating
values, and you can also define custom strategies using `@GenericGenerator`. Here’s
a detailed explanation of the different generation strategies along with examples.
#### a. **AUTO**
**Example**:
```java
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
```
#### b. **IDENTITY**
- **Description**: The database generates the primary key automatically when a new
record is inserted. This is common in databases that support auto-increment
columns.
- **Use Case**: Suitable for databases like MySQL.
**Example**:
```java
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
```
#### c. **SEQUENCE**
**Example**:
```java
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
@SequenceGenerator(name = "user_seq", sequenceName = "user_sequence",
allocationSize = 1)
private Long id;
```
#### d. **TABLE**
**Example**:
```java
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "user_gen")
@TableGenerator(name = "user_gen", table = "id_gen", pkColumnName = "gen_name",
valueColumnName = "gen_val", allocationSize = 1)
private Long id;
```
```java
import org.hibernate.annotations.GenericGenerator;
@Entity
public class User {
@Id
@GeneratedValue(generator = "custom-uuid")
@GenericGenerator(name = "custom-uuid", strategy = "uuid2")
private String id;
1. **@GenericGenerator**:
- The `name` attribute defines the name of the generator ("custom-uuid").
- The `strategy` attribute specifies the generation strategy (`uuid2`), which
generates a UUID.
2. **@GeneratedValue**:
- Links the custom generator to the `id` field. This means whenever a new `User`
entity is persisted, a UUID will be generated for the `id`.
### Summary
Choosing the right generation strategy depends on your specific use case, database
capabilities, and application requirements.
=====================
The `@Temporal` annotation in Hibernate (and JPA) is used to specify how date and
time values should be mapped to the database. It is particularly important when
dealing with the `java.util.Date` or `java.util.Calendar` types.
### Example
Here’s how you can use the `@Temporal` annotation in a Hibernate entity class:
```java
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "events")
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "event_name")
private String eventName;
@Temporal(TemporalType.DATE)
@Column(name = "event_date")
private Date eventDate;
@Temporal(TemporalType.TIME)
@Column(name = "event_time")
private Date eventTime;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "event_timestamp")
private Date eventTimestamp;
1. **Entity Class**: The `Event` class is marked as an entity with `@Entity` and is
mapped to the `events` table.
2. **Primary Key**: The `id` field is the primary key, generated automatically.
3. **Event Name**: The `eventName` field is a simple string representing the name
of the event.
4. **Event Date**:
- Annotated with `@Temporal(TemporalType.DATE)`, which means only the date part
(year, month, day) will be stored in the database. The time portion will be
ignored.
5. **Event Time**:
- Annotated with `@Temporal(TemporalType.TIME)`, meaning only the time (hours,
minutes, seconds) will be stored. The date part will be ignored.
6. **Event Timestamp**:
- Annotated with `@Temporal(TemporalType.TIMESTAMP)`, which stores both date and
time information.
Depending on the database being used, the fields would be mapped to the following
types:
### Summary
The `@Temporal` annotation is essential for correctly mapping date and time fields
in your entity classes to the appropriate database types. It helps ensure that you
store only the relevant parts of date and time as needed for your application.
===================
Got it! Let’s focus on how Hibernate interacts with database tables for creating
and updating them.
- **Entity Definition**: Define your entity class with appropriate JPA annotations.
```java
@Entity
@Table(name = "my_entity")
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
```properties
hibernate.hbm2ddl.auto=create
```
Options include:
- `create`: Drops existing tables and creates new ones.
- `update`: Updates the schema without dropping existing tables.
- `validate`: Validates the schema but does not make changes.
- `none`: No action.
- **Modify the Entity**: Update your entity class by adding a new property.
```java
public class MyEntity {
// Existing fields...
```properties
hibernate.hbm2ddl.auto=update
```
This will alter the existing table to include the new column when the application
starts.
### Summary
- **Table Creation**: Define an entity and set `hibernate.hbm2ddl.auto` to `create`
to have Hibernate generate the table.
- **Table Update**: Modify the entity class and set `hibernate.hbm2ddl.auto` to
`update` to apply changes to the existing table schema.
Make sure to backup your database before using `create` or `update` to prevent
unintended data loss!
=========================
To use a lambda expression with a `List<Employee>`, you typically want to perform
operations like filtering, mapping, or sorting. Here are some common examples using
Java's `Stream` API:
```java
public class Employee {
private String name;
private int age;
private double salary;
```java
List<Employee> employees = // initialize your list here
```java
List<String> employeeNames = employees.stream()
.map(Employee::getName)
.collect(Collectors.toList());
```
```java
List<Employee> sortedBySalary = employees.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary))
.collect(Collectors.toList());
```
```java
double totalSalary = employees.stream()
.mapToDouble(Employee::getSalary)
.sum();
```
```java
boolean hasHighSalary = employees.stream()
.anyMatch(e -> e.getSalary() > 100000);
```
### Summary
**Department.java**
```java
import javax.persistence.*;
import java.util.Set;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
**Employee.java**
```java
import javax.persistence.*;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
```java
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
transaction.commit();
session.close();
```
In this case, when you save the `department`, both `emp1` and `emp2` will
automatically be saved due to the `CascadeType.ALL` setting on the `employees`
collection.
If you want to delete a department and its employees, you can do the following:
```java
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
transaction.commit();
session.close();
```
### Orphan Removal
The `orphanRemoval = true` setting ensures that if an employee is removed from the
`employees` set, it will be deleted from the database:
```java
department.getEmployees().remove(emp1); // emp1 will be deleted from the database
```
### Summary
1. **Object-Oriented**: HQL queries are written against the entity model rather
than the database schema. This allows developers to work with their domain model
directly.
3. **Abstracted from SQL**: HQL abstracts away many of the complexities of SQL,
allowing you to focus more on the object model.
1. **Parsing**: When you write an HQL query, Hibernate parses the query string to
understand its structure.
3. **Execution**: The translated SQL is then executed against the database, and the
results are mapped back to entity objects.
4. **Result Handling**: The results returned by the database are converted back
into instances of your entity classes.
Let’s consider a simple example with two entities: `Author` and `Book`.
```java
@Entity
public class Author {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private Set<Book> books;
}
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
}
```
```java
String hql = "FROM Author";
Query query = session.createQuery(hql);
List<Author> authors = query.list();
```
**Explanation**:
- This query retrieves all `Author` entities.
- Internally, Hibernate translates this to a SQL statement like `SELECT * FROM
Author`.
```java
String hql = "FROM Book b WHERE b.author.name = :authorName";
Query query = session.createQuery(hql);
query.setParameter("authorName", "John Doe");
List<Book> books = query.list();
```
**Explanation**:
- This query retrieves all `Book` entities written by an author with the name "John
Doe".
- Hibernate translates it to an SQL query with a join, as it needs to fetch data
from both the `Book` and `Author` tables.
3. **Aggregating Results**
```java
String hql = "SELECT COUNT(b) FROM Book b";
Query query = session.createQuery(hql);
Long bookCount = (Long) query.uniqueResult();
```
**Explanation**:
- This query counts the number of `Book` entities.
- Hibernate constructs an SQL query like `SELECT COUNT(*) FROM Book`.
4. **Updating Data**
```java
String hql = "UPDATE Author a SET a.name = :newName WHERE a.id = :authorId";
Query query = session.createQuery(hql);
query.setParameter("newName", "Jane Doe");
query.setParameter("authorId", 1L);
int result = query.executeUpdate();
```
**Explanation**:
- This updates the name of the author with a specific ID.
- Hibernate translates this to an SQL update statement.
### Conclusion
1. **Type Safety**: Criteria queries are type-safe, meaning that they check for
correctness at compile time rather than runtime, reducing the likelihood of errors.
2. **Dynamic Queries**: You can build queries dynamically by adding criteria based
on user input or other conditions.
3. **Support for Projections**: You can specify which fields to return, allowing
you to retrieve only the data you need.
4. **Root Entities**: The root entity can be defined easily, allowing you to
navigate through associations.
Let’s continue with our previous example of `Author` and `Book` entities.
```java
@Entity
public class Author {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private Set<Book> books;
}
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToOne
@JoinColumn(name = "author_id")
private Author author;
}
```
```java
Session session = sessionFactory.openSession();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Author> criteriaQuery = criteriaBuilder.createQuery(Author.class);
Root<Author> root = criteriaQuery.from(Author.class);
criteriaQuery.select(root);
**Explanation**:
- `CriteriaBuilder` is used to create the `CriteriaQuery`.
- `Root` defines the root entity for the query.
- Finally, the query is executed, returning a list of `Author` entities.
```java
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Author> criteriaQuery = criteriaBuilder.createQuery(Author.class);
Root<Author> root = criteriaQuery.from(Author.class);
criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("name"), "John
Doe"));
**Explanation**:
- `criteriaBuilder.equal` adds a condition to filter authors with the name "John
Doe".
```java
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Book> criteriaQuery = criteriaBuilder.createQuery(Book.class);
Root<Book> bookRoot = criteriaQuery.from(Book.class);
Join<Book, Author> authorJoin = bookRoot.join("author");
criteriaQuery.select(bookRoot).where(criteriaBuilder.equal(authorJoin.get("name"),
"John Doe"));
**Explanation**:
- `Join` is used to navigate from the `Book` entity to the `Author` entity.
- The query retrieves books written by "John Doe".
4. **Projection Queries**
```java
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<String> criteriaQuery = criteriaBuilder.createQuery(String.class);
Root<Book> bookRoot = criteriaQuery.from(Book.class);
criteriaQuery.select(bookRoot.get("title"));
**Explanation**:
- The query selects only the `title` field from `Book`, returning a list of titles.
5. **Ordering Results**
```java
criteriaQuery.select(bookRoot).orderBy(criteriaBuilder.asc(bookRoot.get("title")));
List<Book> orderedBooks = session.createQuery(criteriaQuery).getResultList();
```
**Explanation**:
- The `orderBy` method specifies that the results should be ordered ascending by
the `title` field.
### Conclusion
1. **Database Schema**: Ensure that your database column for salary allows `NULL`
values. For example, in SQL, you would define your table like this:
```sql
CREATE TABLE Employee (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
salary DOUBLE NULL
);
```
2. **Entity Class Configuration**: In your entity class, you can define the
`salary` field as `Double` (the wrapper class) instead of `double` (the primitive
type). This allows the salary to be `null`.
```java
@Entity
public class Employee {
@Id
@GeneratedValue
private Long id;
private String name;
private Double salary; // Use Double instead of double
3. **Setting Salary to Null**: When creating or updating an `Employee`, you can set
the salary to `null` as needed.
```java
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(employee);
transaction.commit();
session.close();
```
```java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
@Entity
public class Employee {
@Id
@GeneratedValue
private Long id;
private String name;
private Double salary; // Wrapper class to allow null
session.save(employee);
transaction.commit();
session.close();
sessionFactory.close();
}
}
```
### Summary
1. **Use `Double` instead of `double`**: This allows you to set the salary to
`null`.
2. **Ensure database column allows `NULL`**: Define your database schema to accept
`NULL` values.
3. **Set the salary to `null`**: When creating or updating the entity, you can
explicitly set the salary to `null`.
This approach will enable you to store a `NULL` salary in your database correctly.
===================
Hibernate provides a powerful caching mechanism to improve performance by reducing
the number of database queries. There are two primary levels of caching in
Hibernate: **First-Level Cache** and **Second-Level Cache**. Additionally, there is
a **Query Cache** that can be used in conjunction with the second-level cache.
Let’s explore each level in detail.
**Example**:
```java
Session session1 = sessionFactory.openSession();
Transaction transaction1 = session1.beginTransaction();
// Fetching an entity
Author author1 = session1.get(Author.class, 1L); // Hits the database
Author author2 = session1.get(Author.class, 1L); // Hits the first-level cache
transaction1.commit();
session1.close();
```
**Explanation**:
- The first `get()` call fetches the `Author` entity from the database.
- The second `get()` call retrieves the same entity from the first-level cache,
avoiding a second database hit.
**Example Configuration**:
```xml
<property name="hibernate.cache.use_second_level_cache">true</property>
<property
name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegi
onFactory</property>
```
// Usage
Session session1 = sessionFactory.openSession();
Author author1 = session1.get(Author.class, 1L); // Hits the database
session1.close();
**Explanation**:
- The first session fetches the `Author` from the database.
- The second session retrieves the same `Author` from the second-level cache,
avoiding a database hit.
### 3. Query Cache
- **Definition**: The query cache stores the results of a query and can be used in
conjunction with the second-level cache to cache the results of HQL or Criteria
queries.
- **Configuration**: It must be enabled in the Hibernate configuration.
**Example Configuration**:
```xml
<property name="hibernate.cache.use_query_cache">true</property>
```
// Subsequent call with the same parameters will hit the query cache
List<Author> cachedAuthors = query.list(); // Hits the query cache
```
**Explanation**:
- The first query execution fetches data from the database.
- Subsequent executions of the same query with the same parameters retrieve the
results from the query cache.
1. **First-Level Cache**:
- Session-scoped
- Enabled by default
- Not shared across sessions
2. **Second-Level Cache**:
- Session-factory scoped
- Optional and configurable
- Shared across sessions
3. **Query Cache**:
- Caches query results
- Works in conjunction with the second-level cache
### Conclusion
### 1. **Docker**
- **Description**: The most popular and widely used container engine that allows
developers to package applications with all their dependencies into a container. It
is known for its simplicity and efficiency.
- **Use Cases**: Development, testing, continuous integration, and deployment of
applications.
### 2. **Podman**
- **Description**: A daemon-less container engine for developing, managing, and
running OCI containers. It is compatible with Docker but does not require a running
daemon.
- **Use Cases**: Run containers without the need for a background service or
daemon, making it ideal for system-level containerization.
### 3. **CRI-O**
- **Description**: A lightweight container engine designed specifically to run
Kubernetes pods. It is an implementation of Kubernetes Container Runtime Interface
(CRI).
- **Use Cases**: Running containers as part of Kubernetes clusters with minimal
overhead.
### 4. **containerd**
- **Description**: An industry-standard core container runtime that is used as
an underlying engine for Docker. It focuses on simplicity and portability.
- **Use Cases**: Efficient container management in a production environment,
Kubernetes runtime integration.
These container engines have different features and are suited for different use
cases, ranging from lightweight development environments to heavy-duty production
deployments.
=================
Here are the steps and commands for deploying an application to Docker Hub:
### Prerequisites:
1. **Install Docker** on your machine:
- Follow the official guide to install Docker on
[Ubuntu](https://docs.docker.com/engine/install/ubuntu/) or
[Windows](https://docs.docker.com/desktop/windows/install/).
2. **Create a Docker Hub account**:
- Go to [Docker Hub](https://hub.docker.com/) and create an account if you don't
have one.
---
```Dockerfile
# Example Dockerfile
FROM ubuntu:latest # Use the base image (e.g., ubuntu)
WORKDIR /app # Set working directory
- Make sure you adjust the `Dockerfile` according to your app requirements (e.g.,
if it's a Java or Node.js app).
```bash
docker build -t <docker-username>/<image-name>:<tag> .
```
For example:
```bash
docker build -t naresh/my-app:1.0 .
```
This command will build the image with the name `my-app` and the tag `1.0` for user
`naresh`.
```bash
docker run -p 8080:8080 <docker-username>/<image-name>:<tag>
```
For example:
```bash
docker run -p 8080:8080 naresh/my-app:1.0
```
This will run your app locally, and you can test it by going to
`http://localhost:8080` in your browser (adjust the port based on your app).
```bash
docker login
```
```bash
docker tag <image-id> <docker-username>/<image-name>:<tag>
```
For example:
```bash
docker tag my-app:1.0 naresh/my-app:1.0
```
```bash
docker push <docker-username>/<image-name>:<tag>
```
For example:
```bash
docker push naresh/my-app:1.0
```
---
```bash
# Step 1: Build the Docker image
docker build -t naresh/my-app:1.0 .
### Notes:
- Replace `<docker-username>` with your Docker Hub username.
- Replace `<image-name>` with the name of your image.
- Replace `<tag>` with the version or tag you want to use for the image.
This process will deploy your application in Docker Hub, and it can be pulled and
run by others using:
```bash
docker pull <docker-username>/<image-name>:<tag>
docker run -p 8080:8080 <docker-username>/<image-name>:<tag>
```
=============================================================** END
**=================================================================================
===========