Only Bca Chap4
Only Bca Chap4
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.
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.
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.
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.
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. }
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.
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.
9
public void createTimer(long duration) {
context.getTimerService().createTimer(duration, "Hello World!");
}
Q. what is Hibernet ?
Advantage of Hibernate:-
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:
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
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.
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.
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:
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