Anda di halaman 1dari 28

PremAseem.

com
A place for different dimensions of my thoughts
Skip to content

Home

Connect

About Me

Video Blog

My Video

Flying

Category Archives: Hibernate


Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping
an object-oriented domain model to a traditional relational database.
13May2013

Hibernatedifference between save() and persist()


Posted in Hibernate
save() method can return that primary key id value which is generated by hibernate and we can see it by
long s = session.save(k);
In this same case, persist() will never give any value back to the client, hope you are clear.
When to use Persist() and when to use save() ?
persist() is well defined. It makes a transient instance persistent. However, it doesnt guarantee that the identifier
value will be assigned to the persistent instance immediately, the assignment might happen at flush time. The spec
doesnt say that, which is the problem I have with persist().
persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries.
This is useful in long-running conversations with an extended Session/persistence context.

A method like persist() is required.


save() does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier
(e.g. identity generator, not sequence), this INSERT happens immediately, no matter if you are inside or outside
of a transaction. This is not good in a long-running conversation with an extended Session/persistence context.

Share this:

Facebook

Email

Twitter1

More

1 Comment
11Mar2013

Hibernate : Named Query


Posted in Hibernate
Often times, developer like to put HQL string literals scatter all over the Java code, this method is hard to maintaine
and look ugly. Fortunately, Hibernate come out a technique called names queries
HQL in annotation

@NamedQueries({
@NamedQuery(
name = "findStockByStockCode",
query = "from Stock s where s.stockCode = :stockCode"
)
})
@Entity
@Table(name = "stock", catalog = "mkyong")
public class Stock implements java.io.Serializable {
...

Native SQL in annotation


@NamedNativeQueries({
@NamedNativeQuery(
name = "findStockByStockCodeNativeSQL",
query = "select * from stock s where s.stock_code = :stockCode",
resultClass = Stock.class
)
})
@Entity
@Table(name = "stock", catalog = "mkyong")

public class Stock implements java.io.Serializable {


...

In native SQL, you have to declare the resultClass to let Hibernate know what is the return type, failed to do it will
caused the exception org.hibernate.cfg.NotYetImplementedException: Pure native scalar queries are not yet
supported.
Call a named query

In Hibernate, you can call the named query via getNamedQuery method.
Query query = session.getNamedQuery("findStockByStockCode")
.setString("stockCode", "7277");
Query query = session.getNamedQuery("findStockByStockCodeNativeSQL")
.setString("stockCode", "7277");
Thanks to : http://www.mkyong.com/hibernate/hibernate-named-query-examples/

Share this:

Facebook

Email

Twitter1

More

hibernate, hql Leave a comment


10Mar2013

Hibernate : Parameter Binding


Posted in Hibernate
Without parameter binding, you have to concatenate the parameter String like this (bad code) :
String hql = "from Stock s where s.stockCode = '" + stockCode + "'";
List result = session.createQuery(hql).list();

Pass an unchecked value from user input to the database will raise security concern, because it can easy get hack by
SQL injection. You have to avoid the above bad code and using parameter binding instead.
Hibernate parameter binding

There are two ways to parameter binding : named parameters or positional.

1. Named parameters

This is the most common and user friendly way. It use colon followed by a parameter name (:example) to define a
named parameter. See examples
Example 1 setParameter

The setParameter is smart enough to discover the parameter data type for you.
String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql)
.setParameter("stockCode", "7277")
.list();
Example 2 setString

You can use setString to tell Hibernate this parameter date type is String.
String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql)
.setString("stockCode", "7277")
.list();
Example 3 setProperties

This feature is great ! You can pass an object into the parameter binding. Hibernate will automatic check the objects
properties and match with the colon parameter.
Stock stock = new Stock();
stock.setStockCode("7277");
String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql)
.setProperties(stock)
.list();

2. Positional parameters
Its use question mark (?) to define a named parameter, and you have to set your parameter according to the position
sequence. See example
String hql = "from Stock s where s.stockCode = ? and s.stockName = ?";
List result = session.createQuery(hql)
.setString(0, "7277")
.setParameter(1, "DIALOG")
.list();

This approach is not support the setProperties function. In addition, its vulnerable to easy breakage because every
change of the position of the bind parameters requires a change to the parameter binding code.
String hql = "from Stock s where s.stockName = ? and s.stockCode = ?";
List result = session.createQuery(hql)
.setParameter(0, "DIALOG")
.setString(1, "7277")
.list();
Conclusion

In Hibernate parameter binding, i would recommend always go for Named parameters, as its more easy to
maintain, and the compiled SQL statement can be reuse (if only bind parameters change) to increase the
performance.

Share this:

Facebook

Email

Twitter1

More

hibernate, hql, parameter binding Leave a comment


10Mar2013

Hibernate : Object states and lifecycle


Posted in Hibernate
An object is in transient state when it is in heap but not persisted or yet not been given to the hibernate session for
persistence.
Once the object/entity is inatilized and exists in memory, however it is not handed over to hibernate, it is in
transient state.
When object is being handled or tracked by hibernate session or is in control of hibernate it is called as persistent
state. Object in this state remains in synch with the database and is managed by the persistence manager.
After the session is close or once hibernate session leaves the control of object it is called as detached state.
Persistent objects become Detached objects when the session is closed. Calling session.evict() on the object
reference or session.clear() will also remove an object from session. These later session operations will be
covered later in class when cache is discussed.

Detached objects can be reassociated and synchronized to the database after a new session is opened. Calling
session.update() or session.saveOrUpdate() on a Detached object reference transitions the Detached object
back to the Persistent state. When a Detached object is reattached, the database is updated with objects
current state; to include changes made while detached.
A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications)
persistent again. This feature enables a programming model for long running units of work that require user thinktime. We call them application transactions, i.e., a unit of work from the point of view of the user.
Hence once the object is persisted, it transition is mainly in between two states detached and attached (persistent) in
its life cycle. It can also come back to transient state only if call delete() in session.

Share this:

Facebook

Email

Twitter1

More

hibernate Leave a comment


10Mar2013

Hibernate : The Object-Relational


Impedance Mismatch
Posted in Hibernate

Persistence
Hibernate is concerned with helping your application to achieve persistence. So what is persistence? Persistence
simply means that we would like our applications data to outlive the applications process. In Java terms, we would
like the state of (some of) our objects to live beyond the scope of the JVM so that the same state is available later.

Relational Databases
Specifically, Hibernate is concerned with data persistence as it applies to relational databases (RDBMS). In the
world of Object-Oriented applications, there is often a discussion about using an object database (ODBMS) as
opposed to a RDBMS. We are not going to explore that discussion here. Suffice it to say that RDBMS remain a
very popular persistence mechanism and will so for the foreseeable future.

The Object-Relational Impedance Mismatch


Object-Relational Impedance Mismatch (sometimes called the paradigm mismatch) is just a fancy way of saying
that object models and relational models do not work very well together. RDBMSs represent data in a tabular format
(a spreadsheet is a good visualization for those not familiar with RDBMSs), whereas object-oriented languages, such
as Java, represent it as an interconnected graph of objects. Loading and storing graphs of objects using a tabular
relational database exposes us to 5 mismatch problems
1. Granularity
Sometimes you will have an object model which has more classes than the number of corresponding tables in the
database (we says the object model is more granular than the relational model). Take for example the notion of an
Address
2. Subtypes (inheritance)
Inheritance is a natural paradigm in object-oriented programming languages. However, RDBMSs do not define
anything similar on the whole (yes some databases do have subtype support but it is completely non-standardized)
3. Identity
A RDBMS defines exactly one notion of sameness: the primary key. Java, however, defines both object identity
(a==b) and object equality (a.equals(b)).
4. Associations
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMSs use the
notion of foreign keys. If you need bidirectional relationships in Java, you must define the association twice.

Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.
5. Data navigation
The way you access data in Java is fundamentally different than the way you do it in a relational database. In Java,
you navigate from one association to an other walking the object network.
This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number
of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the
object network.

Share this:

Facebook

Email

Twitter1

More

hibernate Leave a comment


10Mar2013

Hibernate : use of mappedBy


Posted in Hibernate
Relationship is something in which two objects are related in some way. Now in object orientation it not necessary
that both the side must show same relationship status,
For example :
I love her (1 to 1)
however she might love others (1 to many)
Now when we want to delegate the responsibility of maintaining the relationship on other side that time we can use
mappedBy, In this way we might not require join table as well. In this case a separate join table can also be avoided.

Share this:

Facebook

Email

Twitter1

More

hibernate, mappings Leave a comment


10Mar2013

Hibernate : Differences in @one-To-Many relation and


@ElementCollection
Posted in Hibernate
This is for sure that to maintain one to many relation we need to have a collection reference in the source object
class. Then what is the difference between the two ?
In simple words, a join table will always get created when using @ElementCollection, however the join table can be
avoided if
@OneToMany(mappedBy = driver) here drive is the member variable from other entity.

How to decide what kind should be used when ?


I believe @ElementCollection is mainly for mapping non-entities (embeddable or basic) while @OneToMany is
used to map entities. So which one to use depend on what you want to achieve.
ElementCollection is a standard
CollectionOfElements.

JPA annotation, which is now preferred over the proprietary Hibernate annotation

It means that the collection is not a collection of entities, but a collection of simple types (Strings, etc.) or a
collection of embedded elements (class annotated with @Embedded).
It also means that the elements are completely owned by the containing entities: theyre modified when he entity is
modified, deleted when the entity is deleted, etc. They cant have their own lifecycle.

Share this:

Facebook

Email

Twitter2

More

collection, hibernate, mappings Leave a comment


27Jan2011

Hibernate Annotation @Embedded


Posted in Computers, Framework, Hibernate
@Embeddable annotation is used to avoid mapping and define component in an entity for re-usability.
Lets say a table Student have the below fields
Student id
Student name
Address line 1
Address line 2
Address line 3
In database it would be represented with a tupple or single row.
More than one students can also reside at the same address. Example students living in a hostel. For the same to save
object heap space, instead of creating one entity we can break it in two entity where in one will get embadedded into
another with primary key. We can split it as :
Student Entity
Student id
Student name
Address (reference of object which gets embedded in Db table)
Address Entity
Address line 1
Address line 2
Address line 3
Now, we can resuse the address object in the students as mentioned in below code snippet.
try {
transaction = session.beginTransaction();
Address address = new Address(Address line 1, Address line 2, Address line 3);
Student student1 = new Student(Eswar, address);

Student student2 = new Student(Prem, address);


Student student3 = new Student(Aseem, address);
session.save(student1);
session.save(student2);
session.save(student3);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
The @Embedded annotation is used to specify the Address entity should be stored in the STUDENT table as a
component.
@Embeddable annotation is used to specify the Address class will be used as a component. The Address class cannot
have a primary key of its own, it uses the enclosing class primary key.
It is possible to declare an embedded component inside an entity and even override its column mapping.

Share this:

Facebook

Email

Twitter

More

2 Comments
18Jan2011

Hibernate Lazy Loading

Posted in Computers, Framework, Hibernate


An object may contents reference of other object and those other object may have reference of other objects, just like
a exponential chain or graph. When we load an object with entire object graph created all at once in the first attempt,
it fires the construction of lot of objects in branch which gives a performance hit and slows the main object creation.
So to avoid this delay, Lazy Loading concept is introduced.
In lazy load the main object is loaded only with bare required properties like id and few data types, however the
composition and other reference object are not loaded at the very first time. So the object is created quickly and
becomes available for use in the application. When ever the child or composite objects are called on the main object
reference, their are created and supplied on the need basis.
Hence the main object is loaded at first time without its children, and children are loaded lazily on the need basis.
The pattern is like this:
public Entity getEntity() {
if (entity == null) {
entity = loadEntity();
}
return entity;
}
This saves the cost of preloading/prefilling all the entities in a large dataset beforehand while you after all actually
dont need all of them.
In Hibernate, you can configure to lazily load a collection of child entities. The actual lazy loading is then done
inside the methods of the PersistentSet which Hibernate uses under the hoods to assign the collection of entities as
Set.
E.g.
public class Parent {
private Set<Child> children;
public Set<Child> getChildren() {
return children;
}
}
.
public void doSomething() {
Set<Child> children = parent.getChildren(); // Still contains nothing.
// Whenever you call one of the following (indirectly),
// Hibernate will start to actually load and fill the set.
children.size();
children.iterator();
}

Share this:

Facebook

Email

Twitter

More

Leave a comment
17Jan2011

what is hibernate saveOrUpdate


Posted in Computers, Hibernate
Difference between hibernates save,update and saveOrUpdate() methods. These are the data insertions methods and
they are called on the session object.
save save method stores an object into the database. That means it insert an entry if the identifier doesnt exist, else
it will throw error. If the primary key already present in the table, it cannot be inserted.
update update method in the hibernate is used for updating the object using identifier. If the identifier is missing or
doesnt exist, it will throw exception.
saveOrUpdate This method calls save() or update() based on the operation. If the identifier exists, it will call
update method else the save method will be called.
saveOrUpdate Cascade=true saves the object graph of the composition object as well.
The sample code to understand save, update, saveOrUpdate with cascade :
/////////////////////////////////////////////////////////////////////////

import java.util.*;
import org.hibernate.*;
import org.hibernate.criterion.*;
public class SimpleRetrieveTest {
public static void main(String[] args) {
HibernateUtil.setup(create table EVENTS ( uid int, name VARCHAR, start_Date date, duration int, location_id int)
;);

HibernateUtil.setup(create table locations ( uid int, name VARCHAR, street_address VARCHAR, city VARCHAR,
state VARCHAR, zip_Code VARCHAR););
// hibernate code start
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
Location location = new Location();
location.setName(India);
location.getAddress().setStreetAddress(St.);
location.getAddress().setCity(Pune);
location.getAddress().setState(Maharastra);
location.getAddress().setZipCode(411014);
Event event = new Event();
event.setName(Annual Meeting);
event.setDuration(60);
event.setStartDate(createDate(2011, 11, 1));
event.setLocation(location);
//
session.save(location); location object will saved automatically with cascade update property.
session.save(event);
//
session.save(location); location object will saved automatically with cascade
update property.
tx.commit();
HibernateUtil.closeSession();

HibernateUtil.sessionFactory.close();
HibernateUtil.checkData(select * from events);
HibernateUtil.checkData(select * from locations);
// hibernate code end
}
private static Date createDate(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
return calendar.getTime();
}
}
/////////////////////////////////////////////////////////////////////////
import java.io.Serializable;
public class Location implements Serializable{
private Long id;
private String name;
private Address address = new Address();

public Location(String name) { this.name = name;}


public Location() { }
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Address getAddress() { return address; }
public void setAddress(Address address) { this.address = address;}
}
/////////////////////////////////////////////////////////////////////////
<?xml version=1.0?>
<!DOCTYPE hibernate-mapping PUBLIC
-//Hibernate/Hibernate Mapping DTD 3.0//EN
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&#8221;>
<hibernate-mapping >
<class name=Location table=locations>
<id name=id column=uid type=long>
<generator class=increment/>
</id>
<property name=name type=string/>
<component name=address class=Address >
<property name=streetAddress column=street_address type=string/>
<property name=city type=string/>
<property name=state type=string/>
<property name=zipCode column=zip_code type=string/>
</component>
</class>
</hibernate-mapping>
/////////////////////////////////////////////////////////////////////////
<?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&#8221;>
<hibernate-configuration>
<session-factory>
<! Database connection settings >
<property name=connection.driver_class>org.hsqldb.jdbcDriver</property>
<property name=connection.url>jdbc:hsqldb:data/tutorial</property>

<property name=connection.username>sa</property>
<property name=connection.password></property>
<! JDBC connection pool (use the built-in) >
<property name=connection.pool_size>1</property>
<! SQL dialect >
<property name=dialect>org.hibernate.dialect.HSQLDialect</property>
<! Echo all executed SQL to stdout >
<property name=show_sql>true</property>
<mapping resource=Event.hbm.xml/>
<mapping resource=Location.hbm.xml/>
</session-factory>
</hibernate-configuration>
/////////////////////////////////////////////////////////////////////////
import java.io.Serializable;
import java.util.Date;
public class Event implements Serializable {
private Long id;
private int duration;
private String name;
private Date startDate;
private Location location;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Date getStartDate() { return startDate; }
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public int getDuration() { return duration; }
public void setDuration(int duration) {
this.duration = duration;
}
public Location getLocation() { return location; }
public void setLocation(Location location) {
this.location = location;
}

public Event() { }
public Event(String name) { this.name = name; }
}
/////////////////////////////////////////////////////////////////////////
<?xml version=1.0?>
<!DOCTYPE hibernate-mapping PUBLIC
-//Hibernate/Hibernate Mapping DTD 3.0//EN
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&#8221;>
<hibernate-mapping >
<class name=Event table=events>
<id name=id column=uid type=long>
<generator class=increment/>
</id>
<property name=name type=string/>
<property name=startDate column=start_date
type=date/>
<property name=duration type=integer/>
<many-to-one name=location column=location_id class=Location cascade=save-update />
</class>
</hibernate-mapping>
/////////////////////////////////////////////////////////////////////////
public class Address {
private String streetAddress;
private String city;
private String state;
private String zipCode;
public String getStreetAddress() { return streetAddress; }
public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress;}
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public String getZipCode() { return zipCode; }
public void setZipCode(String zipCode) { this.zipCode = zipCode; }
public void parse(String address) {
String[] parts = address.split(\\.);
setStreetAddress(parts[0] + .);
String[] remainingPart = parts[1].split( );
setCity(remainingPart[1].replaceAll(,, ));

setState(remainingPart[2]);
setZipCode(remainingPart[3]);
}
}

Share this:

Facebook

Email

Twitter

More

Leave a comment
17Jan2011

Hibernate An Introduction
Posted in Hibernate
This post the dedicated to a formal introduction to hibernate and its features with some important concepts.
There will be dedicate post for each of the concept for detailed understanding.
Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for
mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational
impedance mismatch problems by replacing direct persistence-related database accesses with high-level object
handling functions.
Hibernates primary feature is mapping from Java classes to database tables (and from Java data types to SQL data
types).
Features of Hibernate:
* Hibernate 3.0 provides three full-featured query facilities: Hibernate Query Language, the newly enhanced
Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database.
* Filters for working with temporal (historical), regional or permissioned data.
* Enhanced Criteria query API: with full support for projection/aggregation and subselects.
* Runtime performance monitoring: via JMX or local Java API, including a second-level cache browser.
* Eclipse support, including a suite of Eclipse plug-ins for working with Hibernate 3.0, including mapping editor,
interactive query prototyping, schema reverse engineering tool.

* Hibernate is Free under LGPL: Hibernate can be used to develop/package and distribute the applications for free.
* Hibernate is Scalable: Hibernate is very performant and due to its dual-layer architecture can be used in the
clustered environments.
* Less Development Time: Hibernate reduces the development timings as it supports inheritance, polymorphism,
composition and the Java Collection framework.
* Automatic Key Generation: Hibernate supports the automatic generation of primary key for your.
* JDK 1.5 Enhancements: The new JDK has been released as a preview earlier this year and we expect a slow
migration to the new 1.5 platform throughout 2004. While Hibernate3 still runs perfectly with JDK 1.2, Hibernate3
will make use of some new JDK features. JSR 175 annotations, for example, are a perfect fit for Hibernate metadata
and we will embrace them aggressively. We will also support Java generics, which basically boils down to allowing
type safe collections.
* EJB3-style persistence operations: EJB3 defines the create() and merge() operations, which are slightly different to
Hibernates saveOrUpdate() and saveOrUpdateCopy() operations. Hibernate3 will support all four operations as
methods of the Session interface.
* Hibernate XML binding enables data to be represented as XML and POJOs interchangeably.
* The EJB3 draft specification support for POJO persistence and annotations.
I will dedicate a seperate post for the below points, just for quick understanding have a glance at them.
Hibernate Query Language(HQL)
Hibernate also provides data query and retrieval facilities using native sql as well as object query language. There
quries are optimzed for databases.
Lazy loading
When fully inflated object graph is not loaded, instead only bare required properties are loaded during first access.
The whole object graph is loaded lazily only when it is required with its members as collection. An object that
doesnt contain all of the data you need but knows how to get it. It come by default in Hibernate and is useful in
performance in one to Many mappings.
Database Independend Quries (Dialet sql translater)
Hibernate generates the SQL calls and attempts to relieve the developer from manual result set handling and object
conversion and keep the application portable to all supported SQL databases with little performance overhead.
Mapping (ORM)
Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java
Annotations. When using an XML file, Hibernate can generate skeletal source code for the persistence classes. This
is unnecessary when annotation is used.
Facilities to arrange one-to-many and many-to-many relationships between classes are provided. In addition to
managing association between objects, Hibernate can also manage reflexive associations where an object has a oneto-many relationship with other instances of its own type.
Creates Data base Scehma (Reverse Engineering)
Hibernate can use the XML file or the annotation files to create the databases based on the object mapping into the
database using reverse engineering. This is the configuration which will create DB tables automatically if they do

not exists.
<property name=hibernate.hbm2ddl.auto>update</property>

Share this:

Facebook

Email

Twitter

More

Leave a comment

What is Web Services, Web Services Introduction


Web Services On Jul 6, 2014 By Sivateja
What is Web Services ? Over the internet, you might have seen different kinds of definitions for Web services. My
definition will almost resembles them Web Services, the name it self indicates that its a service which is available
over the Web, thats it. As an example you can consider Java4s.com, When ever you hit the URL in the web browser
it will gives you some output in HTML format, you can also consider this as a Web service. With web services, we
can communicate different applications on different platforms, i mean a java application in Windows platform can
easily communicate with the application developed using .net/php in Linux operation system.

Understanding SOAP and REST


Web Services are mainly of 2 types, SOAP [Simple Object Access Protocol] and REST [Representational state
transfer] based services. We have different type of specifications to implement SOAP and REST services. I believe
so far you might be in confusion with these kind keywords like, JAX-RS, JAX-WS, RESTful, SOAP, Apache Axis2,
Apache CXF bla bla Let me try to bring you out of them.

JAX-RS provides the implementation of RESTful web services, JAX-RS is a specification for RESTful Web
Services with Java and it is given by Sun. Since it is a specification, other frameworks can be written to
implement these specifications, and that includes Jersey from Oracle, Resteasy from Jboss, CXF from
Apache bla bla.

JAX-WS, Apache Axis2 provides the implementation for SOAP

Apache CXF provides implementation for SOAP and RESTful services both.

RESTful

What ever the data/response we will get from the server is known as Resource [remember this point], Each resource
can be accessed by its URIs. We can get the resource from RESTful service in different formats like,
HTML,XML,JSON,TEXT,PDF and in the Image formats as well, but in real time we mainly we will prefer JSON.
REST guidelines always talks about stateless communication between client and the Server. Stateless means, every
single request from client to server will be considered as a fresh request. Because of this reason REST always prefers
to choose HTTP as it a stateless protocol.

RESTful used 4 main HTTP methods

GET - Retrieve Data

POST- Create/Insert Data

PUT- Update Data

DELETE- Delete Data

Generally we will prefer RESTful Services in these scenarios

If clients require caching, means if you have limited bandwidth

If you want every thing to be stateless [ I have already explained about stateless ]

But SOAP gives the output only in XML format. Hope you are good now
to implement JAX-RS specifications.

by the way we are going to use Jersey

Quick Overview On JAX-RS with Java EE 7


JAX-RS Restful Web Services Simple Definition
From Oracle doc. Restful web services is Representational State Transfer (REST) is an architectural style of client-

server application centered around the transfer of representations of resources through requests and responses.
Resources are HTML, XML, plain text, PDF, JPEG, JSON ... and resources are accessed using URIs (PATH =
@Path annotation).
They are manipulated with HTTP requests (GET, POST, PUT, DELETE), and each interaction with a resource is
Stateless.

Most Significant Changes In Java EE 7

WebSocket, it is well married with HTML5 (full duplex compatible Websocket and HTML5 clients).

Improvement of JAX-RS 2 for Restful Web Services

Batch process API

API for caching

JMS 2 is deeply improved

JSON-P

Let's start
Interaction between a web page and JAX-RS uses a set of 4 request types: GET, POST, PUT, DELETE.
Let's take an use case, "Booking Flight Ticket".
The JAX-RS GET request can be "painted" as below.
Annotation in the controller level
@Path(/api)
public class FlightController(){

The POST and PUT requests, are also quite straightforward.

The DELETE request does not differ a lot.

JAX-RS can have @PathParam and @QueryParam in the parameters of their methods as shown the following
snippet codes.
@Path(/flights/{id})
@DELETE
@produces({plain/text})
@Consumes({plain/text})
public String deleteNewFlight(
@PathParam(id) Long id,
@QueryParam(date)String date,
@QueryParam(year)Integer year){
// implemetation
return success;
}

But when to use @PathParam vs. @QueryParam ?


Use @QueryParam for:

optional parameters

pagination and ordering

And @PathPram for situations where one wants to deal with large amount of data, and when one does not want to
transfer in clear the data from the UI to the back-end.
Also remember @QueryParam and @PathPram can be used together in the same method, see figure below.

The other useful annotations

@FormParam

@CookieParam

@HeaderParam

@MatrixParam

@FormParam is used when posting a HTML form

@CookieParam annotation reads information stored as a cookie and @HeaderParam extracts information from
HTTP headers Both are frequently used to manage security
// @CookieParam
@GET
public String getSessionId(@CookieParam(sessionId)String sessionId){ }
// @HeaderParam
@GET
public String getToken(@HeaderPParam(X-Auth-Token)String token){ }

Simularly to @QueryParam, @MatrixParam annotation reads


key1=value1;key2=value2;key3=value3

And the codes below show how @MatrixParam is used.

// @MatrixParam
@GET
public String getAllFlight(
@MatrixParam (month)String month, @MatrixParam (year)Integer year){ }

This is a simple overview on JAX-RS. For more details and examples, just "google", you will find quite good
documentation and tutorials.

Anda mungkin juga menyukai