Java Unit 5 - 23410741 - 2023 - 11 - 22 - 12 - 42

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

www.moreacademy.

online

More Academy

ENTERPRISE JAVA
SEM : V
SEM V: UNIT 5

607A, 6th floor, Ecstasy business park, city of joy, JSD


road, mulund (W) | 8591065589/022-25600622

Abhay More abhay_more


MORE ACADEMY BSC IT: SEM – V JAVA: U5

Page 1 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

1. What is Persistence? Explain with an example. (NOV 18, NOV 19)

Persistence is one of the fundamental concepts of application development. It allows DATA to


outlive the execution of an application that created it. It is one of the most vital pieces of an application
without which all the data is simply lost. Majority of applications use persistent data. For example, GUI
applications need to store user preferences across program invocations, Web applications track user
movements and orders over long periods of time. Hence, it is imperative to choose an appropriate
persistence data store. Often when choosing the persistence data store the following fundamental
qualifiers are considered:
Persistence in the context of computer science and database management refers to the ability to
retain data over time, typically beyond the duration of a program's execution or the lifetime of the
system. Persistence allows data to be stored, retrieved, and managed in a way that it can survive
system restarts, application shutdowns, or even hardware failures. Persistence is crucial for many
software applications, particularly those that need to store and manage data for future use. Here are
some key aspects of persistence:

1. The length of time data must be persisted

2. The volume of data

Example:
<%@page import="org.hibernate.*, org.hibernate.cfg.*, mypack.*" %>
<%! SessionFactory sf;

org.hibernate.Session hibSession; %>

<%
sf = new Configuration().configure().buildSessionFactory();
hibSession = sf.openSession();
Transaction tx = null;
GuestBookBean gb = new GuestBookBean();
try{
tx = hibSession.beginTransaction();
String username = request.getParameter("name");
String usermsg = request.getParameter("message");
String nowtime = ""+new java.util.Date();
gb.setVisitorName(username);
gb.setMsg(usermsg);
gb.setMsgDate(nowtime);
hibSession.save(gb);
tx.commit();
out.println("Thank You for your valuable feedback....");
}catch(Exception e){out.println(e);}
hibSession.close();
%>

Page 2 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

2. With the help of a diagram explain JPA architecture. (APR 18, , NOV 19, APR 23)
• Persistence: The javax.persistence.Persistence class contains static helper methods to
obtain EntityManagerFactoryinstances in a vendor-neutral fashion.
• EntityManagerFactory: The EntityManagerFactory is created with the help of a Persistence Unit
during the application start up. It serves as a factory for spawning EntityManager objects when
required. Typically, it is created once [one EntityManagerFactory object per database] and for later
use kept alive for later use.The javax.persistence.EntityManagerFactory class is a factory for
EntityManagers.
• EntityManager: The EntityManager object [javax.persistence.EntityManager] is lightweight and
inexpensive to create. It provides the main interface to perform actual database operations. All the
POJOs i. e. persistent objects are saved and retrieved with the help of EntityManager object.
Typically, EntityManager objects are created as needed and destroyed when not required. Each
EntityManager manages a set of persistent objects and has APIs to insert new Objects and delete
existing ones. EntityManagers also act as factories for Query instances and CriteriaQuery
instances.
• Entity: Entites are persistent objects that represent datastore records.
• Entity Transaction: A Transaction represents a unit of work with the database. Any kind of
modifications initiated via the EntityManager object are placed within a transaction. An
EntityManager object helps creating an EntityTransaction object. Transaction Objects are typically
used for a short time and are closed by either committing or rejecting.
• Query: Persistent objects are retrieved using a Query object. Query objects
[javax.persistence.Query] allows using SQL or Java Persistence Query Language [JPQL] queries to
retrieve the actual data from the database and create objects.
• Criteria: Criteria API IS a non-string-based API for the dynamic construction of object-based queries
[javax.persistence.criteria]. Just like JPQL static and dynamic queries, criteria query objects are
passed to the EntityManager’screateQuery() method to create Query objects and then executed
using the methods of the Query API. A CriteriaQuery object can be thought of as a set of nodes
corresponding to the semantic constructs of the query:
Domain objects, which correspond to the range variables and other identification variables of the JPQL
FROM clause WHERE clause predicates, which comprise one or more conditional expression objects
SELECT clauses, which comprise one or more select item objects
ORDER-BY and GROUP-BY items Subqueries

Page 3 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

3. What is Hibernate? Explain the need of using it. (NOV 18, NOV 22)

Any project that requires database interaction have started looking at ORM tools than considering
the traditional approach i.e. JDBC. Hibernate ease the job of programmer in working with traditional
database using concrete SQL queries in Java by using java object mapped with data base and allow
programmer to interact with database just like other java class or object. The objective of Hibernate is
to free the programmer from tedious database interaction and focus on working with java objects and
features of application instead of worrying about how to work with data from database. Hibernate
does this by copying data from database table to java class and saving state of an object to database
table. Hibernate is a free, open source, high performance persistent ORM and query tool.

Hibernate provides:

Mapping of java classes to Database table.


e.g.: Student.java class → Student table in Oracle

Mapping of java data type to SQL data type.


e.g.: int → number, String → varchar, java.sql.Date → DateTime, etc.

Flexibility in Querying and retrieving data from any database.

Freedom to switch to any data base without changing the application logic/presentation logic.

Hibernate is an open-source Java framework that provides an object-relational mapping (ORM)


solution for Java applications. It simplifies the process of persisting Java objects (POJOs - Plain Old
Java Objects) into relational databases and retrieving them from the database. Hibernate is widely
used in Java-based enterprise and web applications for database interaction. Here's an explanation of
Hibernate and the need for using it:

Need for Using Hibernate:

1. Abstraction of Database Complexity: Hibernate abstracts the low-level database operations,


SQL, and JDBC, making it easier for developers to work with databases without extensive knowledge
of database internals.

2. Improved Productivity: Developers can focus on application logic rather than writing complex
SQL queries and data mapping code. This results in faster development and reduced boilerplate
code.

3. Database Portability: Hibernate enables applications to run on different databases with minimal
code changes. This is beneficial when your application needs to support multiple database vendors.

4. Object-Oriented Paradigm: Hibernate bridges the gap between the object-oriented programming
(OOP) paradigm used in Java and the relational database model. It allows developers to work with
Java objects, which are more natural to object-oriented development.

5. Optimized Performance: Hibernate's caching mechanisms and lazy loading help optimize
database access and reduce the overhead of fetching unnecessary data.

6. Scalability: By reducing database access and optimizing queries, Hibernate helps improve the
scalability of applications, allowing them to handle more concurrent users.

Page 4 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

7. Transaction Support: Hibernate integrates with transaction management frameworks, ensuring


that database transactions are managed correctly, promoting data integrity.

8. Community and Ecosystem: Hibernate has a large and active user community, which means
access to resources, documentation, and third-party integrations.

In summary, Hibernate simplifies database interaction in Java applications, providing an ORM


solution that makes it easier to work with databases and improving developer productivity. It is a
valuable tool for building robust and maintainable applications that require database persistence.

Page 5 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

4. What are the different components of Hibernate? (NOV 18, NOV 22, APR 23)

Hibernate is an open-source Java framework that provides an object-relational mapping (ORM)


solution for Java applications. It simplifies the process of persisting Java objects (POJOs - Plain Old
Java Objects) into relational databases and retrieving them from the database. Hibernate is widely
used in Java-based enterprise and web applications for database interaction. Here's an explanation of
Hibernate and the need for using it:

Components of Hibernate:
The main components of Hibernate are:

Hibernate is a comprehensive ORM (Object-Relational Mapping) framework for Java applications,


and it consists of several key components that work together to provide database persistence and
management. Here are the different components of Hibernate:

1. Hibernate Configuration:

- Hibernate Configuration File: The configuration starts with a `hibernate.cfg.xml` file or a


programmatic configuration object. This file or object specifies database connection details, dialect,
connection pool settings, and other Hibernate properties.

2. Session Factory:

- Session Factory: The Session Factory is a thread-safe, immutable cache of compiled mapping
metadata. It is a central concept in Hibernate and serves as a factory for creating Session instances.
The Session Factory is typically built once during application startup and shared throughout the
application's lifecycle.

3. Mapping Metadata:

- Mapping Information: Hibernate maps Java objects (entities) to database tables. The mapping
metadata includes XML or annotation-based mappings that define how Java classes and properties
correspond to database tables and columns.

4. Session Management:

- Session: A Session is a short-lived, lightweight object representing a single unit of work with the
database. It encapsulates a JDBC connection and is responsible for managing the lifecycle of
persistent objects, executing SQL queries, and coordinating transactions.

5. Transaction Management:

- Transaction: Hibernate supports transaction management, allowing you to demarcate and control
transactions explicitly. It integrates with Java Transaction API (JTA) for global transactions and
provides programmatic and declarative transaction support.

6. Query Language:

- HQL (Hibernate Query Language): HQL is a powerful query language similar to SQL but
operates on Hibernate-managed entities. It allows you to express database queries using object-
oriented syntax, making it database-agnostic.

- Criteria API: Hibernate offers a Criteria API for constructing type-safe queries using a fluent,
object-oriented API. It is particularly useful when query conditions are generated dynamically.

Page 6 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

- Native SQL: You can execute native SQL queries when needed, although Hibernate encourages
the use of HQL or Criteria API for better portability.

7. Caching:

- First-Level Cache: Every Session has a first-level cache (also known as the Session cache),
which stores persistent objects during a session's lifetime. This cache improves performance by
reducing database round-trips.

- Second-Level Cache: Hibernate supports second-level caching, which is a shared cache that
spans multiple sessions. It stores cached data in a distributed cache provider (e.g., EHCache,
Infinispan) and can significantly boost performance.

8. Transaction Synchronization:

- Transaction Synchronization: Hibernate provides hooks for synchronizing database-related


operations with the underlying transaction. This is particularly useful for integrating with other
frameworks and services.

9. Listeners and Interceptors:

- Listeners: Hibernate supports event listeners that allow you to customize and respond to various
Hibernate lifecycle events, such as object loading, saving, or deleting.

- Interceptors: Interceptors can intercept and modify SQL statements, entity lifecycle events, and
property values, offering a way to customize Hibernate behavior.

10. Dialects:

- Dialect: Hibernate includes dialect-specific implementations for various relational databases. The
dialect is responsible for generating database-specific SQL statements and handling database-
specific features.

11. Toolset:

- Tools and Utilities: Hibernate provides a range of tools and utilities for code generation, schema
generation, and database schema updates.

These components work together to provide a powerful and flexible ORM framework, allowing Java
applications to interact with relational databases in a high-level, object-oriented manner while
ensuring efficient and optimized database access.

Page 7 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

5. Write a short note on hibernate architecture. (NOV 19, APR 23)

Hibernate is a layered architecture. The main components are Configuration, Session Factory,
Session, Transaction, Query and Criteria. Hibernate uses existing Java APIs, like JDBC for database
connectivity, Java Transaction API(JTA) for transaction and Java Naming and Directory Interface
(JNDI) for easy integration with other enterprise application

Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming
and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction offunctionality
common to relational databases, allowing almost any database with a JDBC driver to supported by
Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.
Configuration: It represents properties/configuration of a hibernate application. It the first object created
in a hibernate application and created once at the time of application execution. This object reads the
configuration file to establish database connection and mapping. This object helps in creating session
factory. It represents a configuration or properties file required by the Hibernate. The Configuration
object provides two keys components:
• Database Connection: This is handled through one or more configuration files supported by
Hibernate. These files are hibernate.properties and hibernate.cfg.xml.

• Class Mapping Setup This component creates the connection between the Java classes and
database tables.

Page 8 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

Session Factory: It is created using configuration object at the time of application startup to
serve as a base for creating light weight sessions conveniently during client’s request. One
session factory is created for one database for multiple database multiple session factory
objects are created. Session Object: Sessions are single threaded, lightweight objects to
communicate with database represented by session class from org.hinernate package.
Persistent object are created, saved and retrieved using session object during client interaction.
It wraps the Connection class from java.sql package and serves as factory for Transaction. The
session objects should not be kept open for a long time because they are not usually thread
safe and they should be created and destroyed them as needed.
Transaction: Transaction is a single threaded object used by application to represent group of
SQL queries to form a unit of work called transaction. Transactions in Hibernate are handled by
an underlying transaction manager and transaction (from JDBC or JTA). All changes during a
session are placed within transaction. Transactions are either completed using commit or
cancelled using rollback. The org.hibernate.Transaction interface provides methods for
transaction management.
Query: It uses either conventional SQL or Hibernate Query Language (HQL) to communicate
with database. It associates the query parameters, restricts the results coming from database
and executes queries. Persistent objects are retrieved using query object.
Criteria: Criteria objects are used to create and execute object oriented criteria queries to
retrieve objects.

Page 9 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

6. Write a JSP code to add visitor’s feedback using Hibernate in FeedBack table in database. (
NOV 19)

<%@page import="org.hibernate.*, org.hibernate.cfg.*, mypack.*" %>


<%! SessionFactory sf;
org.hibernate.Session hibSession; %>

<%
sf = new Configuration().configure().buildSessionFactory();
hibSession = sf.openSession();
Transaction tx = null;
GuestBookBean gb = new GuestBookBean();
try{
tx = hibSession.beginTransaction();
String username = request.getParameter("name");
String usermsg = request.getParameter("message");
String nowtime = ""+new java.util.Date();
gb.setVisitorName(username);
gb.setMsg(usermsg);
gb.setMsgDate(nowtime);
hibSession.save(gb);
tx.commit();
out.println("Thank You for your valuable feedback....");
}catch(Exception e){out.println(e);}
hibSession.close();
%>

Page 10 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

7. Write a JSP code to add guest feedback using JPA in GuestBook table in database.(APR 19)

<%@page import="java.util.*,javax.persistence.*,mypack.GuestBook" %>


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
private EntityTransaction entityTransaction;
%>
<%
entityManagerFactory = Persistence.createEntityManagerFactory("JPAApplication1PU");
entityManager = entityManagerFactory.createEntityManager();
String submit = request.getParameter("btnSubmit");
try {
String guest = request.getParameter("guest");
String message = request.getParameter("message");
String messageDate = new java.util.Date().toString();
GuestBook gb = new GuestBook();
gb.setVisitorName(guest);
gb.setMessage(message);
gb.setMessageDate(messageDate);
entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
entityManager.persist(gb);
entityTransaction.commit();
} catch (RuntimeException e) {
if(entityTransaction != null) entityTransaction.rollback();
throw e; }
try {
guestbook = entityManager.createQuery("SELECT g from GuestBook
g").getResultList();
} catch (RuntimeException e) { }
entityManager.close();%>

Page 11 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

8. What is Impedance Mismatch? How it can be solved? (NOV 18, APR 19, APR 23)

The object oriented [domain] model use classes, whereas the relational databases use tables. This
creates a gap [The Impedance Mismatch]. Getting the data and associations from objects into relational
table structure and vice versa requires a lot of tedious programming due to the difference between the
two. This difference is called The Impedance Mismatch.

The Impedance Mismatch:

This issue arises as the design of relational data and object-oriented instances share a very different
relationship structure within their respective environments. Relational databases are structured in a
tabular manner and the object-oriented instances are structured in a hierarchical manner. This means
that in this object-oriented world, data is represented as OBJECTS [often Called DOMAIN model].
However, the storage medium is based on a RELATIONAL paradigm. Hence, there exists an inevitable
mismatch, the so-called Object/Relational Impedance Mismatch which creates a vacuum between the
Object-Oriented Model of a well-designed application [the DOMAIN model] and the relational model in a
database schema. This vacuum is surprisingly wide.

Page 12 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

9. What is the relationship between JPA, ORM, Database and the application? (APR 19)

JPA is made up of a few classes and interfaces. The application communicates with the
configured IPA provider [in this case EclipseLink] to access the underlying data. Typically, applications
invoke the appropriate methods of the Java Persistence API.

These methods are passed the persistence objects and instructed to operate upon them. The
information about the mapping [metadata] between the instance variables of classes and the columns
of the tables in the database is available either in XML and/ or POJOs with the help of Annotations.

POJOs are Java classes that represent the tables in the database. Data Access Object [DAO] is the
design pattern that can be used [if required] to deal with database operations.’

EclipseLink uses the database [using JDBC API internally] and refers to the metadata to provide
persistence services [and Persistent Objects] to the application. The application talks to EclipseLink via
the JPA to perform the SELECT, INSERT, UPDATE and DELETE operations on the database tables.

The ORM tool automatically creates the required SQL queries and fires them using the JDBC APIs.

Page 13 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

10. Write short note on Functions in JPQL and Downcasting in JPQL. (NOV 22) (APR 19)

JPQL (Java Persistence Query Language) is a platform-independent query language used in Java
applications that employ the Java Persistence API (JPA). JPA is a Java EE standard that allows developers
to perform Object-Relational Mapping (ORM), enabling them to interact with relational databases using
Java objects and classes.

JPQL is similar in purpose to SQL (Structured Query Language) but differs in syntax and usage. It is
designed to work with JPA entities, which are Java classes representing database tables.

Functions in JPQL:
JPA supports a set of database functions which you can use to perform small operations and
transformations within a query. This is often easier and faster than doing it in the Java code. SQL
supports a lot more database functions than JPQL, Specific database vendors also provide their own set
of functions. Users and libraries can also define their own database functions. JPA 2.0 JPQL provided
no mechanism to call database specific functions.
JPA 21 introduced function() to call database functions which are not directly supported by the standard.
The syntax is very easy. You need to provide the name of the function as the first parameter and then all
parameters of the custom function. In following example, the name of the function is "calculate" and I
provide the numbers 1 and 2 as parameters.
Example:
Author a = em.createQuery("SELECT a FROM Author a WHERE a.id = function('calculate', 1, 2)",
Author.class).getSingleResult();

Downcasting in JPQL:
JPQL will be extended to cast in the FROM and WHERE clause. The format of this will use the keyword
"TREAT" and be part of the join clause. The operator TREAT can be used to cast an entity to its
subclass value, i.e. downcast related entities with inheritance. This is typically used in JOIN queries
where we want to impose a restriction in WHERE clause involving a subclass field. The following is an
example:

Example:
select e from Employee e join TREAT(e.projects AS LargeProject) lp where lp.attribute = value

Page 14 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

11. How hibernate works? / Explain the modus operandi behind hibernate application. (NOV 18,
APR 19, , NOV 19, NOV 22, APR 23)

Hibernate is an Object-Relational Mapping (ORM) framework for Java applications that simplifies database
interaction by mapping Java objects to database tables. It provides a high-level, object-oriented approach
to database operations, allowing developers to work with Java objects rather than writing SQL queries
directly. Here's how Hibernate works:

1. Configuration:

- Hibernate is configured using a configuration file (typically `hibernate.cfg.xml`) or programmatic


configuration. This configuration specifies database connection details, dialect, and other settings.

2. Entity Classes:

- Developers define entity classes that represent database tables. These classes are annotated with
Hibernate annotations or configured using XML mappings. Each entity class corresponds to a table, and its
attributes correspond to table columns.

3. Session Factory:

- Hibernate uses a Session Factory to create and manage sessions. The Session Factory is a
heavyweight, thread-safe, and immutable object that serves as a factory for creating individual sessions.

• All configuration files hibernate.cfg.xml are created to describe about the java classes and there
mapping with database tables.
• At the time of application startup these files are compiled to provide hibernate framework with
necessary information.
• This dynamically builds java class objects by mapping them to appropriate database table.
• A session factory object is created from compiled collections of mapping documents.
• Session Factory spawns a lightweight session to provide interface between java objects and
applications.

• Database communication is performed by this session using hibernate API used to map the changes
from java object to database table and vice versa.

Page 15 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

12. Explain the structure of hibernate.cfg.xml. (APR 19)

Hibernate requires to know in advance that, where to find the mapping information that defines how
your Java classes relate to the database tables. Hibernate also requires a set of configuration settings
related to database and other related parameters. All such information is usually supplied as a standard
Java properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml.

We will consider XMI. formatted file hibernate.cfg.xml to specify required Hibernate properties in
following example. Most of the properties take their default values and it is not required to specify them
in the property file unless it is really required. This file is kept in the root directory of your application's
classpath.

We will be required to configure for a databases in a standalone situation following properties:

• hibernate.dialect: This property makes Hibernate generate the appropriate SQL for the chosen
database.
• hibernate.connection.driver class: The JDBC driver class.

• hibernate.connection.url: The JDBC URL to the database instance


hibernate.connection.username: The database username.

• hibernate.connection.password: The database password.

• hibernate.connection.pool size: Limits the number of connections waiting in the Hibernate


database connection pool.

• hibernate.connection.autocommit: Allows autocommit mode to be used for the JDBC connection

If you are using a database along with an application server and JNDI, then you would have to
configure the following properties:

• hibernate.connection.datasource: The JNDI name defined in the application server context,


which you are using for the application.
• hibernate.jndi.class: The InitialContext class for JNDL
• hibernate.jndi.<JNDIpropertyname>: Passes any JNDI property you like to the JNDI
InitialContext.
• hibernate.jndi.url: Provides the URL for JNDI.
• hibernate.connection.username: The database username.
• hibernate.connection.password: The database password.

Page 16 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

The following sample file gives some insight of hibernate,cfg.xml file where MySQL is used as
database server for the application.

<?xml version="1.0" encoding="utf-8"?>


<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/java2novice</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">false</property>
</session-factory>
</hibernate-configuration>

Page 17 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

13. Explain tollowing:


i) JOIN condition Using ON
ii) Entity Listeners Using CDI (NOV 22)

i) JOIN Condition Using ON:

In SQL, when you use the `JOIN` operation to combine rows from two or more tables, you typically specify
the conditions for joining those tables in the `ON` clause. The `ON` clause defines how the rows from
different tables are related and dictates which rows should be included in the result set. It allows you to
specify the columns and the comparison logic used to establish the relationship between the tables being
joined.

In relational databases, a JOIN operation is used to combine rows from two or more tables based on a
related column between them. The `ON` clause is an integral part of a `JOIN` statement, specifying the
conditions under which rows from the joined tables are matched. The `ON` clause is used to define the
relationship between the tables and is essential for retrieving the desired results from the query.
ON clause can be used to join columns that have different names. Use the ON clause to specify conditions
or specify columns to join. The join condition is separated from other search conditions. This is the most
easiest and widely used form of the join clauses.

ii) Entity Listeners Using CDI (Contexts and Dependency Injection):

In the context of Java EE (now known as Jakarta EE) and CDI (Contexts and Dependency Injection), Entity
Listeners are components that allow you to define and execute custom logic before or after certain
database operations on entities. These listeners are typically used in conjunction with JPA (Java
Persistence API) entities to perform additional actions or validations when entities are created, updated, or
deleted.

In Java EE (Enterprise Edition) and Jakarta EE, Entity Listeners are components that allow you to define
callback methods that are executed when certain lifecycle events occur on JPA (Java Persistence API)
entities. These callback methods are useful for performing tasks such as auditing, validation, or any custom
logic when entities are created, updated, or removed.

Contexts and Dependency Injection (CDI) is a part of Java EE (and Jakarta EE) that provides a powerful
dependency injection mechanism and a rich set of capabilities for managing the lifecycle of Java EE
components.

When combining Entity Listeners with CDI, you can create CDI beans to act as Entity Listeners. This allows
you to leverage the benefits of CDI within your Entity Listeners, including dependency injection and access
to CDI services.

Page 18 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

14. Where Does Java Persistence API Fit In? (NOV 22)

The Java Persistence API (JPA) is a Java EE (Enterprise Edition) and Jakarta EE standard that fits into
the larger ecosystem of Java-based enterprise applications and is primarily used for working with relational
databases. It plays a crucial role in simplifying and standardizing database access and object-relational mapping
(ORM) within Java EE and Jakarta EE applications. Here's where JPA fits in:

1. Database Interaction:
- JPA provides a standard way to interact with relational databases from Java applications. It abstracts the low-
level JDBC (Java Database Connectivity) code and allows developers to work with Java objects that represent
database records.

2. Object-Relational Mapping (ORM):


- JPA facilitates the mapping of Java objects to database tables. It defines a set of annotations and XML
configuration for defining the mapping between Java classes and database tables, columns, and relationships.
This makes it easier to work with data in an object-oriented manner.

3. Persistence Units:
- In a JPA application, you define one or more "persistence units" in a persistence.xml configuration file. Each
persistence unit specifies the set of entities (Java classes) that are managed by the JPA provider and the
database connection settings.

4. Entity Classes:
- Entity classes are plain Java classes annotated with JPA annotations (e.g., `@Entity`, `@Table`,
`@JoinColumn`). These classes represent the structure of the database tables and the relationships between
them. JPA takes care of translating between Java objects and database records.

5. Entity Manager:
- JPA applications use an `EntityManager` to interact with the database. The `EntityManager` is responsible for
managing the lifecycle of entities, performing CRUD (Create, Read, Update, Delete) operations, and executing
queries using a standardized query language called JPQL (Java Persistence Query Language).

6. Transaction Management:
- JPA integrates with the transaction management system of Java EE or Jakarta EE. It allows you to work
within transactional boundaries, ensuring data consistency and integrity. You can use annotations like
`@Transactional` to specify transaction demarcation.

Page 19 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

7. Querying:
- JPA provides a powerful query language called JPQL for writing database queries in a database-agnostic
way. JPQL queries are expressed in terms of Java entities and their properties rather than SQL tables and
columns.

8. Integration with Java EE and Jakarta EE:


- JPA is designed to seamlessly integrate with other Java EE and Jakarta EE technologies, such as CDI
(Contexts and Dependency Injection), EJB (Enterprise JavaBeans), and servlets. This allows you to build
comprehensive and modular enterprise applications.

In summary, JPA fits into the broader Java EE and Jakarta EE ecosystem by providing a standardized and
efficient means of managing database access and ORM in enterprise applications. It simplifies database
interaction, enhances portability, and enables developers to work with databases in a more object-oriented
and efficient manner.

Page 20 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622
MORE ACADEMY BSC IT: SEM – V JAVA: U5

Page 21 of 21
YouTube - Abhay More | Telegram - abhay_more
607A, 6th floor, Ecstasy business park, city of joy, JSD road, mulund (W) | 8591065589/022-25600622

You might also like