This article gives you complete overview of Hibernate and EJB and also comparison b/w them.
Comparing EJB and Hibernate
EJBs are supposed to be components, in the sense that they're not just one class, but a set of classes, descriptors (thats an XML and/or annotations in EJB 3), usage and management contracts. All of this in order to allow a container (JBoss, Weblogic, etc.) to provide services to those components, and to be able to reuse and distribute this components. This services are, among others, transactions, concurrent access control, security, instance pooling, etcetera.
Hibernate is "just" an ORM (Object/Relational Mapping) tool. Quick and dirty, this means you can store an object tree belonging to an class hierarchy in a relational DB without writing a single SQL query. Very easy way to achieve persistence, IMO. But no transaction control, no instance pooling, no concurrency control, and certainly no security.
Just look at the below simple example to get an idea about persistence using Hibernate,
Hibernate needs configuration file (hibernate.cfg.xml) to create database connection which will look like as below,
<?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.url">jdbc:mysql://localhost:3306/StockMarket</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin123</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.isolation">2</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
<!-- mapping files -->
<mapping resource="com/example/Stock.hbm.xml" />
</session-factory>
</hibernate-configuration>
// The Stock object will be mapped to "Stock" table in Hibernate
public class Stock implements Serializable {
String name;
float price;
// getters and setters for "name" and "price" member variables
...................
}
Stock.hbm.xml will look like,
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.example.Stock" table="Stock" lazy="false">
<id name="name" column="Name" type="string">
<generator class="assigned" />
</id>
<property column="Price" name="price" type="float"/>
</class>
</hibernate-mapping>
One need to write the CRUD (Create, Retrieve, Update and Delete) operation in DAO class to operate/control the Stock object in database. Take a loot at StockDAO class as below,
public final class HibernateUtil {
public static Session getSession() {
return Configuration.configure().buildSessionFactory().getCurrentSession();
}
}
public class StockDAO {
public void addStock(Stock s) {
Session session = HibernateUtil.getSession();
Transaction t = session.getTransaction();
try {
t.beginTransaction();
session.persist(s);
t.commit();
} catch(Exception e) {
t.rollback();
}
}
Look at the below simple example to get an idea about persistence using EJB 2.1,
Note: this example uses the bean-managed way to persit JAVA objects. One more way of persisting is container-managed
// primary key
public class StockBeanPK implement java.io.Serializable {
private String name;
StockBeanPK(String name) { this.name = name;}
public int hashcode() { name.hashcode());
public boolean equals(Object name) { this.name.equals(name);}
}
// entity bean
public interface StockBean extends javax.ejb.EntityBean {
public void setPrice(Float price) throws RemoteException;
}
// home interface
public interface StockHome extends javax.ejb.EJBHome {
public Stock create(Stock s) throws RemoteException, CreateException;
}
// remote interface
public interface Stock extends javax.ejb.EJBObject {
public Stock create(Stock s) throws RemoteException, CreateException;
}
// entity bean object impl
public class StockImpl implements StockBean {
StockBeanPK pk;
float price;
// getters and setters for "price" member variables
...................
}
// remote object impl
public class StockImpl implements Stock {
public Stock create(Stock s) {
InitialContext it = new InitialContext();
// this lookup url refers to the database in which entity beans are persisted
ds = (DataSource)it.lookup("java:comp/env/jdbc/StockMarketDB");
Connection conn = ds.getConnection();
try {
// store Object state in DB
stmt = conn.prepareStatement("insert into stock values(?,?)");
String pk = (String)entityContext.getPrimaryKey();
stmt.setString(1, pk.name);
stmt.setFloat(2, s.getPrice());
stmt.executeUpdate();
} catch (SQLException e) {
throw new javax.ejb.EJBException("Failed to store bean to database", e);
} finally {
try {
if (stmt != null) stmt.close(); // close statement
if (conn != null) conn.close(); // release connection
} catch (Exception ignore) {}
}
}
}
/** Implement the local interface as same as above remote object implementation **/
Look at the below simple example to get an idea about persistence using EJB 3.0,
In EJB3.0, the configuration file (Persistence.xml) looks like as below,
Note: this file is almost same as hibernate.cfg.xml file in Hibernate. EclipseLink is one of the Persistence Provider that wraps the EJB 3.0 implementations.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="tnm_alarm_implPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.example.Stock</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/StockMarket"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
// The Stock entity will be mapped to "Stock" table in EJB3.0 annotations
@Entity
@Table(name="Stock");
public class Stock implements Serializable {
@Id
@Column(name="name")
String name;
@Column(name="price")
float price;
// getters and setters for "name" and "price" member variables
...................
}
public final class EntityManagerEAO {
final String PERSISTENCE_UNIT = "EntityService";
static final emFactory;
private static final Map<String, Object> properties = new HashMap<String, Object>()
{
private static final long serialVersionUID = -6262745355119727515L;
{
put(PersistenceUnitProperties.TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
put("provider", "org.eclipse.persistence.jpa.PersistenceProvider");
put(PersistenceUnitProperties.JDBC_DRIVER, "com.mysql.jdbc.Driver");
put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.NONE);
put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
}
};
public static EntityManager createEntityManager() {
emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
return emFactory.createEntityManager();
}
}
public class StockEAO {
public void addStock(Stock s) {
EntityManager em = EntityManagerEAO.createEntityManager();
try {
em.getTransaction().begin();
em.persist(s);
em.getTransaction().commit();
}
catch(Exception e) {
em.getTransaction().rollback();
}
finally {
em.close();
}
}
}
Overall I conclude that EJB 3.0 is a nice feature to persist JAVA objects and it overcomes all the drawbacks of EJB 2.1 and also inherits the features of Hibernate as well.
Enjoy Persisting JAVA objects!!!
Comparing EJB and Hibernate
EJBs are supposed to be components, in the sense that they're not just one class, but a set of classes, descriptors (thats an XML and/or annotations in EJB 3), usage and management contracts. All of this in order to allow a container (JBoss, Weblogic, etc.) to provide services to those components, and to be able to reuse and distribute this components. This services are, among others, transactions, concurrent access control, security, instance pooling, etcetera.
Hibernate is "just" an ORM (Object/Relational Mapping) tool. Quick and dirty, this means you can store an object tree belonging to an class hierarchy in a relational DB without writing a single SQL query. Very easy way to achieve persistence, IMO. But no transaction control, no instance pooling, no concurrency control, and certainly no security.
Just look at the below simple example to get an idea about persistence using Hibernate,
Hibernate needs configuration file (hibernate.cfg.xml) to create database connection which will look like as below,
<?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.url">jdbc:mysql://localhost:3306/StockMarket</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin123</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.isolation">2</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
<!-- mapping files -->
<mapping resource="com/example/Stock.hbm.xml" />
</session-factory>
</hibernate-configuration>
// The Stock object will be mapped to "Stock" table in Hibernate
public class Stock implements Serializable {
String name;
float price;
// getters and setters for "name" and "price" member variables
...................
}
Stock.hbm.xml will look like,
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.example.Stock" table="Stock" lazy="false">
<id name="name" column="Name" type="string">
<generator class="assigned" />
</id>
<property column="Price" name="price" type="float"/>
</class>
</hibernate-mapping>
One need to write the CRUD (Create, Retrieve, Update and Delete) operation in DAO class to operate/control the Stock object in database. Take a loot at StockDAO class as below,
public final class HibernateUtil {
public static Session getSession() {
return Configuration.configure().buildSessionFactory().getCurrentSession();
}
}
public class StockDAO {
public void addStock(Stock s) {
Session session = HibernateUtil.getSession();
Transaction t = session.getTransaction();
try {
t.beginTransaction();
session.persist(s);
t.commit();
} catch(Exception e) {
t.rollback();
}
}
Look at the below simple example to get an idea about persistence using EJB 2.1,
Note: this example uses the bean-managed way to persit JAVA objects. One more way of persisting is container-managed
// primary key
public class StockBeanPK implement java.io.Serializable {
private String name;
StockBeanPK(String name) { this.name = name;}
public int hashcode() { name.hashcode());
public boolean equals(Object name) { this.name.equals(name);}
}
// entity bean
public interface StockBean extends javax.ejb.EntityBean {
public void setPrice(Float price) throws RemoteException;
}
// home interface
public interface StockHome extends javax.ejb.EJBHome {
public Stock create(Stock s) throws RemoteException, CreateException;
}
// remote interface
public interface Stock extends javax.ejb.EJBObject {
public Stock create(Stock s) throws RemoteException, CreateException;
}
// entity bean object impl
public class StockImpl implements StockBean {
StockBeanPK pk;
float price;
// getters and setters for "price" member variables
...................
}
// remote object impl
public class StockImpl implements Stock {
public Stock create(Stock s) {
InitialContext it = new InitialContext();
// this lookup url refers to the database in which entity beans are persisted
ds = (DataSource)it.lookup("java:comp/env/jdbc/StockMarketDB");
Connection conn = ds.getConnection();
try {
// store Object state in DB
stmt = conn.prepareStatement("insert into stock values(?,?)");
String pk = (String)entityContext.getPrimaryKey();
stmt.setString(1, pk.name);
stmt.setFloat(2, s.getPrice());
stmt.executeUpdate();
} catch (SQLException e) {
throw new javax.ejb.EJBException("Failed to store bean to database", e);
} finally {
try {
if (stmt != null) stmt.close(); // close statement
if (conn != null) conn.close(); // release connection
} catch (Exception ignore) {}
}
}
}
/** Implement the local interface as same as above remote object implementation **/
Look at the below simple example to get an idea about persistence using EJB 3.0,
In EJB3.0, the configuration file (Persistence.xml) looks like as below,
Note: this file is almost same as hibernate.cfg.xml file in Hibernate. EclipseLink is one of the Persistence Provider that wraps the EJB 3.0 implementations.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="tnm_alarm_implPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.example.Stock</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/StockMarket"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
// The Stock entity will be mapped to "Stock" table in EJB3.0 annotations
@Entity
@Table(name="Stock");
public class Stock implements Serializable {
@Id
@Column(name="name")
String name;
@Column(name="price")
float price;
// getters and setters for "name" and "price" member variables
...................
}
public final class EntityManagerEAO {
final String PERSISTENCE_UNIT = "EntityService";
static final emFactory;
private static final Map<String, Object> properties = new HashMap<String, Object>()
{
private static final long serialVersionUID = -6262745355119727515L;
{
put(PersistenceUnitProperties.TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
put("provider", "org.eclipse.persistence.jpa.PersistenceProvider");
put(PersistenceUnitProperties.JDBC_DRIVER, "com.mysql.jdbc.Driver");
put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.NONE);
put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
}
};
public static EntityManager createEntityManager() {
emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties);
return emFactory.createEntityManager();
}
}
public class StockEAO {
public void addStock(Stock s) {
EntityManager em = EntityManagerEAO.createEntityManager();
try {
em.getTransaction().begin();
em.persist(s);
em.getTransaction().commit();
}
catch(Exception e) {
em.getTransaction().rollback();
}
finally {
em.close();
}
}
}
Overall I conclude that EJB 3.0 is a nice feature to persist JAVA objects and it overcomes all the drawbacks of EJB 2.1 and also inherits the features of Hibernate as well.
Enjoy Persisting JAVA objects!!!
No comments:
Post a Comment