0% found this document useful (0 votes)
51 views20 pages

Only Bca Chap4

MVC is an architecture that separates an application into three main components: the model, the view, and the controller. The model manages the behavior and data of the application. The view displays the user interface. The controller interprets inputs from the user and calls methods on the model and tells the view to update. EJB is used to develop scalable, robust, and secure enterprise applications in Java. EJB provides services like security, transaction management, and life cycle management through the EJB container. There are three main types of EJB: session beans, message driven beans, and entity beans. Session beans contain business logic, message driven beans are invoked by messages, and entity beans represent persistent data in databases.

Uploaded by

Patel Vivek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views20 pages

Only Bca Chap4

MVC is an architecture that separates an application into three main components: the model, the view, and the controller. The model manages the behavior and data of the application. The view displays the user interface. The controller interprets inputs from the user and calls methods on the model and tells the view to update. EJB is used to develop scalable, robust, and secure enterprise applications in Java. EJB provides services like security, transaction management, and life cycle management through the EJB container. There are three main types of EJB: session beans, message driven beans, and entity beans. Session beans contain business logic, message driven beans are invoked by messages, and entity beans represent persistent data in databases.

Uploaded by

Patel Vivek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Subject : J2EE

Class : BCA SEM – 5


Chapter: 4 MVC Architecture, EJB, Hibernate

Q.1 What is MVC ? Define with its architecture


What is MVC?
MVC is an architecture that separates business logic, presentation and
data. In MVC,
Model represents the state of the application i.e. data. It can also
have business logic.
View represents the presentaion i.e. UI(User Interface).
Controller acts as an interface between View and Model. Controller
intercepts all the incoming requests.

MVC is a systematic way to use the application where the flow starts
from the view layer, where the request is raised and processed in
controller layer and sent to model layer to insert data and get back the
success or failure message.

1.Model Layer:
 This is the data layer which consists of the business logic of the
system.
 It consists of all the data of the application
 It also represents the state of the application.
 It consists of classes which have the connection to the database.
 The controller connects with model and fetches the data and sends
to the view layer.
 The model connects with the database as well and stores the data
into a database which is connected to it.

1
2.View Layer:
 This is a presentation layer.
 It consists of HTML, JSP, etc. into it.
 It normally presents the UI of the application.
 It is used to display the data which is fetched from the controller
which in turn fetching data from model layer classes.
 This view layer shows the data on UI of the application.
3.Controller Layer:
 It acts as an interface between View and Model.

layer.
 ocesses the
requests and does the necessary validation for the request.

and once the request is processed, it sends back to the controller
with required information and displayed accordingly by the view.

Advantage:
 Easy to maintain.
 Easy to extend.
 Easy to test

2
Disadvantage:
We need to write the controller code self.
If we change the controller code, we need to recompile the class and
redeploy the application.

Q.2 What is EJB.


EJB (Enterprise Java Bean) is used to develop scalable, robust and
secured enterprise applications in java.
Unlike RMI, middleware services such as security, transaction
management etc. are provided by EJB Container to all EJB applications.
The current version of EJB is EJB 3.2. The development of EJB 3 is
faster than EJB 2 because of simplicity and annotations such as @EJB,
@Stateless, @Stateful, @ModelDriven, @PreDestroy, @PostConstruct
etc.
To run EJB application, you need an application server (EJB Container)
such as Jboss, Weblogic, Websphere etc.
It performs:
a. life cycle management,
b. security,
c. transaction management, and
EJB application is deployed on the server, so it is called server side
component also.
EJB is like COM (Component Object Model) provided by Microsoft.
But, it is different from Java Bean, RMI and Web Services.

Q.3 Discuss Benefits and restriction of EJB


Following are the important benefits of EJB −
Simplified development of large-scale enterprise level application.
Application Server/EJB container provides most of the system level
services like transaction handling, logging, load balancing, persistence
mechanism, exception handling, and so on. Developer has to focus only
on business logic of the application.

3
EJB container manages life cycle of EJB instances, thus developer
needs not to worry about when to create/delete EJB objects.

Disadvantages of EJB
Requires application server
Requires only java client. For other language client, you need to go for
webservice.
Complex to understand and develop ejb applications.

Q.4 Explain types of EJB.


There are 3 types of enterprise bean in java.
A) Session Bean : Session bean contains business logic that can be
invoked by local, remote or web service client.
B) Message Driven Bean : Like Session Bean, it contains the business
logic but it is invoked by passing message.
C) Entity Bean : It encapsulates the state that can be persisted in the
database. It is deprecated. Now, it is replaced with JPA (Java Persistent
API).
A) Session Bean
Session bean encapsulates business logic only, it can be invoked by
local, remote and webservice client.
It can be used for calculations, database access etc.
The life cycle of session bean is maintained by the application server
(EJB Container).

Types of Session Bean


There are 3 types of session bean.
1) Stateless Session Bean: It doesn't maintain state of a client between
multiple method calls.
2) Stateful Session Bean: It maintains state of a client across multiple
requests.

4
3) Singleton Session Bean: One instance per application, it is shared
between clients and supports concurrent access.
1) Stateless Session Bean:
Stateless Session bean is a business object that represents business
logic only. It doesn't have state (data).
In other words, conversational state between multiple method calls is
not maintained by the container in case of stateless session bean.
The stateless bean objects are pooled by the EJB container to service
the request on demand.
It can be accessed by one client at a time. In case of concurrent
access, EJB container routes each request to different instance.

Annotations used in Stateless Session Bean


There are 3 important annotations used in stateless session bean:
1. @Stateless
2. @PostConstruct
3. @PreDestroy

Life cycle of Stateless Session Bean


There is only two states of stateless session bean: does not exist and
ready. It is explained by the figure given below.

5
EJB Container creates and maintains a pool of session bean first. It
injects the dependency if then calls the @PostConstruct method if any.
Now actual business logic method is invoked by the client.
Then, container calls @PreDestory method if any. Now bean is ready
for garbage collection.

Example of Stateless Session Bean


To develop stateless bean application, we need to use Eclipse IDE and
glassfish 3 server.
To create EJB application, you need to create bean component and
bean client.
1) Create stateless bean component
To create the stateless bean component, you need to create a remote
interface and a bean class.
File: AdderImplRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3.
4. @Remote
5. public interface AdderImplRemote {
6. int add(int a,int b);
7. }

File: AdderImpl.java
1. package com.javatpoint;
2. import javax.ejb.Stateless;
3.
4. @Stateless(mappedName="st1")
5. public class AdderImpl implements AdderImplRemote {
6. public int add(int a,int b){
7. return a+b;

6
8. }
9. }

2) Create stateless bean client


The stateless bean client may be local, remote or webservice client.
Here, we are going to create remote client. It is console based
application.
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.naming.Context;
3. import javax.naming.InitialContext;
4.
5. public class Test {
6. public static void main(String[] args)throws Exception {
7. Context context=new InitialContext();
8. AdderImplRemote
remote=(AdderImplRemote)context.lookup("st1");

9. System.out.println(remote.add(32,32));
10. }
11. }

Output
Output: 64
2) Stateful Session Bean:
Stateful Session bean is a business object that represents business
logic like stateless session bean. But, it maintains state (data).
In other words, conversational state between multiple method calls is
maintained by the container in stateful session bean.

Annotations used in Stateful Session Bean


There are 5 important annotations used in stateful session bean:
7
1. @Stateful
2. @PostConstruct
3. @PreDestroy
4. @PrePassivate
5. @PostActivate

3) Singleton Session Bean: One instance per application, it is shared


between clients and supports concurrent access.

B) Message Driven Bean


A message driven bean (MDB) is a bean that contains business logic.
But, it is invoked by passing the message. So, it is like JMS Receiver.
MDB asynchronously receives the message and processes it.
A message driven bean receives message from queue or topic, so you
must have the knowledge of JMS API.

Message-driven beans have the following characteristics:


• They execute upon receipt of a single client message.
• They are invoked asynchronously.
• They are relatively short-lived.
• They do not represent directly shared data in the database, but they
can access and update this data.
• They can be transaction-aware.
• They are stateless.

C) Entity Bean

8
 Entity bean represents the persistent data stored in the database. It
is a server-side component.
 In EJB 2.x, there was two types of entity beans: bean managed
persistence (BMP) and container managed persistence (CMP).
 Since EJB 3.x, it is deprecated and replaced by JPA (Java Persistence
API).
 An entity bean represents a business object in a persistent storage
mechanism. Some examples of business objects are customers,
orders, and products. In the Application Server, the persistent
storage mechanism is a relational database. Typically, each entity
bean has an underlying table in a relational database, and each
instance of the bean corresponds to a row in that table.

Q.5 what is timer service


Timer Service is a mechanism by which scheduled application can be
build.
For example, salary slip generation on the 1st of every month.
EJB 3.0 specification has specified @Timeout annotation, which helps
in programming the EJB service in a stateless or message driven bean.
EJB Container calls the method, which is annotated by @Timeout.
EJB Timer Service is a service provided by EJB container, which helps
to create timer and to schedule callback when timer expires.
Use SessionContext object to get TimerService and to create timer.
Pass time in milliseconds and message.
 Applications that model business work flows often rely on timed
notifications. The timer service of the enterprise bean container
enables you to schedule timed notifications for all types of enterprise
beans except for stateful session beans. You can schedule a timed
notification to occur at a specific time, after duration of time, or at
timed intervals. For example, you could set timers to go off at 10:30
AM on May 23, in 30 days, or every 12 hours.
EX.

9
public void createTimer(long duration) {
context.getTimerService().createTimer(duration, "Hello World!");
}

Q. what is Hibernet ?

Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and


it raised as an open source persistent framework created by Gavin King
in 2001. It is a powerful, high performance Object-Relational
Persistence and Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data
types to SQL data types and relieve the developer from 95% of common
data persistence related programming tasks.

Hibernate sits between traditional Java objects and database server to


handle all the work in persisting those objects based on the appropriate
O/R mechanisms and patterns.

Advantage of Hibernate:-

XML files and without writing any line of code.


Provides simple APIs for storing and retrieving Java objects directly to
and from the database.

change XML file properties.


work
around familiar Java Objects.

10
ata.

Q. Hibernate Architecture:
The Hibernate architecture is layered to keep you isolated from having
to know the underlying APIs. Hibernate makes use of the database and
configuration data to provide persistence services (and persistent
objects) to the application.

11
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 of functionality common to
relational databases, allowing almost any database with a JDBC driver
to be supported by Hibernate. JNDI and JTA allow Hibernate to be
integrated with J2EE application servers.

Configuration Object:
The Configuration object is the first Hibernate object you create in any
Hibernate application and usually created only once during application
initialization. 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.
SessionFactory Object:
Configuration object is used to create a SessionFactory object which
inturn configures Hibernate for the application using the supplied
12
configuration file and allows for a Session object to be instantiated. The
SessionFactory is a thread safe object and used by all the threads of an
application. The SessionFactory is heavyweight object so usually it is
created during application start up and kept for later use. You would
need one SessionFactory object per database using a separate
configuration file. So if you are using multiple databases then you
would have to create multiple SessionFactory objects.
Session Object:
A Session is used to get a physical connection with a database. The
Session object is lightweight and designed to be instantiated each time
an interaction is needed with the database. Persistent objects are saved
and retrieved through a Session object.
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 Object:
A Transaction represents a unit of work with the database and most of
the RDBMS supports transaction functionality. Transactions in
Hibernate are handled by an underlying transaction manager and
transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to
use this interface, instead managing transactions in their own
application code.
Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to
retrieve data from the database and create objects. A Query instance is
used to bind query parameters, limit the number of results returned by
the query, and finally to execute the query.
Criteria Object:
Criteria object are used to create and execute object oriented criteria
queries to retrieve objects.

Q. Downloading Hibernate:
13
It is assumed that you already have latest version of Java is installed on
your machine. Following are the simple steps to download and install
Hibernate on your machine.
Make a choice whether you want to install Hibernate on Windows, or
UNIX and then proceed to the next step to download .zip file for
windows and .tz file for UNIX.
Download the latest version of Hibernate from
http://www.hibernate.org/downloads.
At the time of writing this tutorial I downloaded hibernate-distribution-
3.6.4.Final and when you unzip the downloaded file it will give you
directory structure as follows.

Installing Hibernate:
Once you downloaded and unzipped the latest version of the Hibernate
Installation file, you need to perform following two simple steps. Make
sure you are setting your CLASSPATH variable properly otherwise you
will face problem while compiling your application.
Now copy all the library files from /lib into your CLASSPATH, and
change your classpath variable to include all the JARs:

Hibernate Prerequisites:

Following is the list of the packages/libraries required by Hibernate


and you should install them before starting with Hibernate. To install
these packages you would have to copy library files from /lib into
your CLASSPATH, and change your CLASSPATH variable

14
S.N. Packages/Libraries
1 dom4j - XML parsing www.dom4j.org/
2 Xalan - XSLT Processor http://xml.apache.org/xalan-j/
3 Xerces - The Xerces Java Parser http://xml.apache.org/xerces-
j/
4 cglib - Appropriate changes to Java classes at runtime
http://cglib.sourceforge.net/
5 log4j - Logging Faremwork http://logging.apache.org/log4j
6 Commons - Logging, Email etc.
http://jakarta.apache.org/commons
7 SLF4J - Logging Facade for Java http://www.slf4j.org

Q. Jar files of Hibernate :


Let us see what are the jar files we need to download to work with
hibernate framework, and how to install.
Working with the framework software is nothing but, adding the
.jar(s) files provided by that framework to our java application. Each
framework software is not an installable software, it means we do not
contain any setup.exe
When we download any framework software, we will get a ‘zip‘ file
and we need to unzip it, to get the jar files required, actually all
framework softwares will follow same common principles like…

one jar file acts as main (We can call this file as core) and remaining
will acts as dependent jar files.
on xml
file, but multiple configuration files also allowed.

environment into a java application, the configuration file is the first


one to be loaded into a java application, will see about this in later
sessions.

15
Where to download Hibernate .jar(s) files:
we can download jars related to hibernate at
http://sourceforge.net/projects/hibernate/files/hibernate3
From the above URL choose hibernate 3.2.2-ga.zip, as we are in initial
stage this version will be better.
Unzip it, and now you can find some jar files in the lib folder right..?,
actually we doesn’t require all the jar files, out of them just select the
following jar files..
-Anttr-2.7.6.jar
-asm.jar
-asm-attrs.jar
-cglib-2.1.3.jar
-commons-collections-2.1.1.jar
-ehcash.jar
-dom4j-1.6.1.jar
-hibernate3.jar
-jta.jar
-log4j-1.2.3.jar

Q.Hibernate Configuration
Hibernate requires to know in advance 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.

S.N. Properties and Description


1 hibernate.dialect This property makes Hibernate generate the
appropriate SQL for the chosen database.

16
2 hibernate.connection.driver_class The JDBC driver class.
3 hibernate.connection.url The JDBC URL to the database instance.
4 hibernate.connection.username The database username.
5 hibernate.connection.password The database password.
6 hibernate.connection.pool_size Limits the number of
connections waiting in the Hibernate database connection pool.
7 hibernate.connection.autocommit Allows autocommit mode to
be used for the JDBC connection.
Q.Hibernate Mapping Files
An Object/relational mappings are usually defined in an XML
document. This mapping file instructs Hibernate how to map the
defined class or classes to the database tables.
Though many Hibernate users choose to write the XML by hand, a
number of tools exist to generate the mapping document. These
include XDoclet, Middlegen and AndroMDA for advanced Hibernate
users.

17
Q. Hibernet Annotation
Hibernate annotations is the newest way to define mappings without a
use of XML file. You can use annotations in addition to or as a
replacement of XML mapping metadata.
Hibernate Annotations is the powerful way to provide the metadata for
the Object and Relational Table mapping. All the metadata is clubbed
into the POJO java file along with the code this helps the user to
understand the table structure and POJO simultaneously during the
development.

Q. Hibernate Sessions
A Session is used to get a physical connection with a database. The
Session object is lightweight and designed to be instantiated each time
an interaction is needed with the database. Persistent objects are saved
and retrieved through a Session object.
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. The main function of the Session is to offer
create, read and delete operations for instances of mapped entity
classes. Instances may exist in one of the following three states at a
given point in time:

transient: A new instance of a a persistent class which is not associated


with a Session and has no representation in the database and no
identifier value is considered transient by Hibernate.
persistent: You can make a transient instance persistent by
associating it with a Session. A persistent instance has a representation
in the database, an identifier value and is associated with a Session.
detached: Once we close the Hibernate Session, the persistent
instance will become a detached instance.

No Session Methods and Description

18
1 Transaction beginTransaction() Begin a unit of work and return
the associated Transaction object.
2 void cancelQuery() Cancel the execution of the current query.
3 void clear() Completely clear the session.
4 Connection close() End the session by releasing the JDBC
connection and cleaning up.
7 Serializable getIdentifier(Object object) Return the identifier value
of the given entity as associated with this session.
10 SQLQuery createSQLQuery(String queryString) Create a new
instance of SQLQuery for the given SQL query string.
11 void delete(Object object) Remove a persistent instance from the
datastore.
13 Session get(String entityName, Serializable id) Return the
persistent instance of the given named entity with the given
identifier, or null if there is no such persistent instance.
15 void refresh(Object object) Re-read the state of the given instance
16 Transaction getTransaction() :Get the Transaction instance
associated with this session.
17 boolean isConnected() :Check if the session is currently
connected.
18 boolean isDirty(): Does this session contain any changes which
must be synchronized with the database?
19 boolean isOpen() :Check if the session is still open.
20 Serializable save(Object object): Persist the given transient
instance, first assigning a generated identifier.
21 void saveOrUpdate(Object object): Either save(Object) or
update(Object) the given instance.
22 void update(Object object): Update the persistent instance with
the identifier of the given detached instance.

19
Q.Hibernate Inheritance:-
Compared to JDBC we have one main advantage in hibernate, which is
hibernate inheritance. Suppose if we have base and derived classes,
now if we save derived(sub) class object, base class object will also be
stored into the database. But the thing is we must specify in what table
we need to save which object data
Hibernate supports 3 types of Inheritance Mappings:
Table per class hierarchy
Table per sub-class hierarchy
Table per concrete class hierarchy

20

You might also like