com
A place for different dimensions of my thoughts
Skip to content
Home
Connect
About Me
Video Blog
My Video
Flying
Share this:
Twitter1
More
1 Comment
11Mar2013
@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 {
...
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:
Twitter1
More
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
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:
Twitter1
More
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:
Twitter1
More
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.
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:
Twitter1
More
Share this:
Twitter1
More
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:
Twitter2
More
Share this:
More
2 Comments
18Jan2011
Share this:
More
Leave a comment
17Jan2011
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();
<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”>
<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:
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:
More
Leave a comment
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.
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.
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.
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.
WebSocket, it is well married with HTML5 (full duplex compatible Websocket and HTML5 clients).
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(){
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;
}
optional parameters
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.
@FormParam
@CookieParam
@HeaderParam
@MatrixParam
@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){ }
// @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.