<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java Bulgaria &#187; Uncategorized</title>
	<atom:link href="http://javabg.eu/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>http://javabg.eu</link>
	<description>Всичко за Java</description>
	<lastBuildDate>Tue, 24 Jan 2012 16:46:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to decompress serialized object from a Gzip file</title>
		<link>http://javabg.eu/2010/02/how-to-decompress-serialized-object-from-a-gzip-file/</link>
		<comments>http://javabg.eu/2010/02/how-to-decompress-serialized-object-from-a-gzip-file/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 12:24:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://javabg.eu/?p=385</guid>
		<description><![CDATA[In last section, you learn about how to compress a serialized object into a file, now you learn how to decompress it from a Gzip file. FileInputStream fin = new FileInputStream("c:\\address.gz"); GZIPInputStream gis = new GZIPInputStream(fin); ObjectInputStream ois = new ObjectInputStream(gis); address = (Address) ois.readObject(); GZIP example In this example, you will decompress a compressed [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>In last section, you learn about how to compress a serialized object into a file,  now you learn how to decompress it from a Gzip file.</p>
<div>
<div>
<pre style="font-family: monospace;"><span style="color: #003399;">FileInputStream</span> fin <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">FileInputStream</span><span style="color: #009900;">(</span><span style="color: #0000ff;">"c:<span style="color: #000099; font-weight: bold;">\\</span>address.gz"</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
<span style="color: #003399;">GZIPInputStream</span> gis <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">GZIPInputStream</span><span style="color: #009900;">(</span>fin<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
<span style="color: #003399;">ObjectInputStream</span> ois <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ObjectInputStream</span><span style="color: #009900;">(</span>gis<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
address <span style="color: #339933;">=</span> <span style="color: #009900;">(</span>Address<span style="color: #009900;">)</span> ois.<span style="color: #006633;">readObject</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span></pre>
</div>
</div>
<h4>GZIP example</h4>
<p>In this example, you will decompress a compressed file “<strong>address.gz</strong>“,  and print it out the value.</p>
<div>
<div>
<pre style="font-family: monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.mkyong.io</span><span style="color: #339933;">;</span>

<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.FileInputStream</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.ObjectInputStream</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.Serializable</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.zip.GZIPInputStream</span><span style="color: #339933;">;</span>

<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Deserializer <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Serializable</span><span style="color: #009900;">{</span>

   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main <span style="color: #009900;">(</span><span style="color: #003399;">String</span> args<span style="color: #009900;">[</span><span style="color: #009900;">]</span><span style="color: #009900;">)</span> <span style="color: #009900;">{</span>

	   Deserializer deserializer <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Deserializer<span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
	   Address address <span style="color: #339933;">=</span> deserializer.<span style="color: #006633;">deserialzeAddress</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
	   <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">(</span>address<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">}</span>

   <span style="color: #000000; font-weight: bold;">public</span> Address deserialzeAddress<span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #009900;">{</span>

	   Address address<span style="color: #339933;">;</span>

	   <span style="color: #000000; font-weight: bold;">try</span><span style="color: #009900;">{</span>

		   <span style="color: #003399;">FileInputStream</span> fin <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">FileInputStream</span><span style="color: #009900;">(</span><span style="color: #0000ff;">"c:<span style="color: #000099; font-weight: bold;">\\</span>address.gz"</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
		   <span style="color: #003399;">GZIPInputStream</span> gis <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">GZIPInputStream</span><span style="color: #009900;">(</span>fin<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
		   <span style="color: #003399;">ObjectInputStream</span> ois <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ObjectInputStream</span><span style="color: #009900;">(</span>gis<span style="color: #009900;">)</span><span style="color: #339933;">;</span>
		   address <span style="color: #339933;">=</span> <span style="color: #009900;">(</span>Address<span style="color: #009900;">)</span> ois.<span style="color: #006633;">readObject</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
		   ois.<span style="color: #006633;">close</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>

		   <span style="color: #000000; font-weight: bold;">return</span> address<span style="color: #339933;">;</span>

	   <span style="color: #009900;">}</span><span style="color: #000000; font-weight: bold;">catch</span><span style="color: #009900;">(</span><span style="color: #003399;">Exception</span> ex<span style="color: #009900;">)</span><span style="color: #009900;">{</span>
		   ex.<span style="color: #006633;">printStackTrace</span><span style="color: #009900;">(</span><span style="color: #009900;">)</span><span style="color: #339933;">;</span>
		   <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
	   <span style="color: #009900;">}</span>
   <span style="color: #009900;">}</span>
<span style="color: #009900;">}</span></pre>
</div>
</div>
<h4>Output</h4>
<div>
<div>
<pre style="font-family: monospace;"> Street : <span style="color: #c20cb9; font-weight: bold;">wall</span> street Country : <span id="IL_AD2">united state</span></pre>
</div>
</div>
<img src="http://javabg.eu/?ak_action=api_record_view&id=385&type=feed" alt="" />

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://javabg.eu/2010/02/how-to-decompress-serialized-object-from-a-gzip-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Developing Applications with JBoss and Hibernate: Part 2</title>
		<link>http://javabg.eu/2010/02/developing-applications-with-jboss-and-hibernate-part-2/</link>
		<comments>http://javabg.eu/2010/02/developing-applications-with-jboss-and-hibernate-part-2/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 18:06:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[английски]]></category>
		<category><![CDATA[уроци]]></category>

		<guid isPermaLink="false">http://javabg.eu/?p=359</guid>
		<description><![CDATA[Adding a web client to your project There are several ways to test our Hibernate application. The simplest of all is adding a web application, which is packaged in an enterprise application along with the Hibernate application. Create a new dynamic web project named HibernateWeb. The first step, before adding servlets and JSPs is linking [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<h2>Adding a web client to your project</h2>
<p>There are several ways to  test our Hibernate application. The simplest of all is adding a web  application, which is packaged in an enterprise application along with  the Hibernate application. Create a new dynamic web project named  HibernateWeb.</p>
<p>The first step, before adding servlets and JSPs is  linking the HibernateProject libraries to your web application,  otherwise, you will not be able to reference the Hibernate POJOs.  Right-click on your project and select <strong>Properties</strong>. Reach the <strong>Java  Build Path</strong> option and select the tab <strong>Projects</strong>. From there  add <strong>HibernateProject</strong>.</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article2-image15.png" alt="" /></p>
<p>Let&#8217;s  move on. This project will contain a main servlet that acts as a  controller, and a few JPSs for the client view. We will start by adding <em>com.packtpub.hibernateWeb.HibernateServlet</em> to our project.</p>
<p>In the following snippet, you can see the core  section of the servlet. Here, we will not detail the Controller logic,  which is straightforward if you have some rudiments of the MVC pattern;  rather we want to highlight the most interesting part of it, which is  how to query and persist Hibernate objects.</p>
<pre style="margin-left: 40px;">public class HibernateServlet extends HttpServlet {
private SessionFactory getSessionFactory() {
return (SessionFactory)getServletContext().
getAttribute("sessionFactory");
}
public void init() { [1]
if (getSessionFactory() != null) {
return;
}
InitialContext ctx;
try {
ctx = new InitialContext();
factory = (SessionFactory)ctx.
lookup("java:/hibernate/SessionFactory");
getServletContext().setAttribute("sessionFactory", factory);
}
catch (NamingException e) {
e.printStackTrace();
}
}
private String saveEmployee(HttpServletRequest request) {
Session hsession=null;
String name=request.getParameter("name");
String salary=request.getParameter("salary");
String departmentId=request.getParameter("departmentId");
try {
hsession = getSessionFactory().openSession();
hsession.beginTransaction();
Query query = hsession.createQuery("from Department d where
d.departmentId = :departmentId"); [2]
query.setInteger("departmentId", new Integer(departmentId));
Department dep = (Department) query.uniqueResult();
Employee emp = new Employee();
emp.setDepartment(dep);
emp.setEmployeeName(name);
emp.setEmployeeSalary(Integer.parseInt(salary));
hsession.save(emp); [3]
hsession.getTransaction().commit();
}
catch (Exception e) {
// TODO Auto-generated catch block e.printStackTrace();
hsession.getTransaction().rollback();
}
finally {
if (hsession.isOpen())
hsession.close();
}
return employeeList(request);
}
private String employeeList(HttpServletRequest request) {
Session hsession=null;
Department dep;
try {
hsession = getSessionFactory().openSession();
Query query = hsession.createQuery("select p from Employee p
join fetch p.department c"); [4]
List &lt;Employee&gt;list = query.list();
request.setAttribute("employee", list);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (hsession.isOpen())
hsession.close();
}
return "/listEmployees.jsp";
}
private String saveDepartment(HttpServletRequest request) {
String depName=request.getParameter("depName");
Session hsession=null;
Department dep;
try {
hsession = getSessionFactory().openSession();
hsession.beginTransaction();
dep = new Department();
dep.setDepartmentName(depName);
hsession.save(dep); [5]
hsession.getTransaction().commit();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
hsession.getTransaction().rollback();
}
finally {
if (hsession.isOpen())
hsession.close();
}
return employeeList(request);
}
}</pre>
<p>As  you can see from the preceding code, we recover the <em>SessionFactory</em> from the JNDI tree in the <em>init()</em> <strong>[1]</strong> method of the  servlet. Instances of <em>SessionFactory</em> are thread-safe and  typically shared throughout an application, so we store it in the <em>ServletContext</em> and share it among all servlet instances.</p>
<p>The <em>SessionFactory</em> is subsequently used to start a Hibernate session, which is not  thread-safe and should only be used for a single transaction or unit of  work in an application.</p>
<p>In order to store our <em>Employee</em>, in  the <em>saveEmployee</em> method, we first retrieve the corresponding <em>Department</em> from our schema <strong>[2]</strong>, and finally the <em>Employee</em> is saved <strong>[3]</strong> and the transaction is committed.</p>
<p>The list of employees is  fetched by the <em>employeeList</em> method. Notice we are using a <em>join  fetch</em> statement to retrieve all the employees <strong>[4]</strong>, which  will be routed to the <em>listEmployees.jsp</em> view. Why? The answer is  that with the default fetch mode (Lazy), once the Hibernate session is  closed, the client will not be able to navigate through the <em>department</em> field of the Employee. The common solution to this issue is switching  to the EAGER fetch mode that reads the related fields (in our case  department) in memory, as soon as we query the <em>Employee</em> table.</p>
<p>You  have more than one option to achieve this. One possible solution, if  you don&#8217;t want to change the default fetch mode for the <em>Employee</em> table, is to build an ad hoc query that forces Hibernate to read also  the fields in relation with the <em>Employee</em> table.</p>
<pre style="margin-left: 40px;">"select p from Employee p join fetch p.department c"</pre>
<p>If  you prefer to use the XML class files to configure the fetch mode, you  can also change the <em>lazy=&#8220;true&#8220;</em> attribute in the  employee-department relationship.</p>
<p>The last method, <em>saveDepartment</em> <strong>[5]</strong> takes care to persist a new <em>Department</em> in the  corresponding table. We complete our excursus on the web tier with the <em>listEmployees.jsp</em> that is used to display a tabular view of the employees:</p>
<pre style="margin-left: 40px;">&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %&gt;
&lt;html&gt;
&lt;script language="JavaScript"&gt;
function doSubmit(url) {
document.module.action = url;
document.module.submit();
}
&lt;/script&gt;
&lt;body&gt;
&lt;table border="1"&gt;
&lt;tr&gt;
&lt;th&gt;Name&lt;/th&gt;
&lt;th&gt;Salary&lt;/th&gt; &lt;TH&gt;department&lt;/th&gt;
&lt;/tr&gt;
&lt;c:forEach items="${employee}" var="emp"&gt;
&lt;tr&gt;
&lt;td&gt; &lt;c:out value="${emp.employeeName}"/&gt; &lt;/td&gt;
&lt;td&gt; &lt;c:out value="${emp.employeeSalary}"/&gt;&lt;/td&gt;
&lt;td&gt; &lt;c:out value="${emp.department.departmentName}"/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/c:forEach&gt;
&lt;/table&gt;
&lt;form name="module" method="POST"&gt;
&lt;input type="button" value ="New Employee"
onClick="doSubmit('actionServlet?op=newEmployee')"&gt;
&lt;input type="button" value ="New Department"
onClick="doSubmit('actionServlet?op=newDepartment')"&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>This  page uses JSP 2.0 <strong>Expression Language</strong> (<strong>EL</strong>) to iterate  through the list of employees, as highlighted in the last code snippet.  We have also hightlighted the <em>taglib</em> directive, at the beginning  of the page. This directive will be used to resolve the JSTL core set of  libraries that ships with JBoss AS in the <em>server/xxx/deploy/jbossweb.sar/jstl.jar</em> library. (Eclipse does not contain references to this library when you  create a web project; you have to add <em>jstl.jar</em> to your build  path, otherwise Eclipse will mark it as an error. However, that&#8217;s only a  visual annoyance because the JBoss Web container has got everything it  needs to run JSTL.)</p>
<p>The complete web application is available on  the Packtpub website (http://www.packtpub.com)  and includes two additional JSPs for entering the employee (<em>newEmployee.jsp</em>)  and department (<em>newDepartment.jsp</em>) data, plus one placeholder <em>index.jsp</em> that merely forwards to the Hibernate servlet.</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article2-image16.png" alt="" /></p>
<h2>Packaging and deploying the application</h2>
<p>Y our enterprise  application is complete. We need to package it in an EAR archive so that  the web application will be able to interact with the Hibernate POJOs.  Create a new <strong>Enterprise Application</strong> project from the Java EE  folder. You will be prompted to select the projects that will be  included as modules. Select both the <strong>HibernateProject</strong> and the web  application <strong>HibernateWeb</strong>.</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article2-image17.png" alt="" /></p>
<p>If  you have ever worked with JBoss AS and Hibernate, then you might argue  that right now something is missing. You&#8217;re indeed right. Before release  5.0 of the JBoss Application Server, Hibernate classes and mapping  files had to be packaged in a JBoss AS custom <em>.har</em> archive. The  suffix was determinant, as JBoss AS was able to classify the package as a  Hibernate resource.</p>
<p>As HAR archives are not Java EE standard  components, you have to declare it in a JBoss AS-specific configuration  file named <em>jboss-app.xml</em> that sits in the <em>META-INF</em> folder  of our EAR.</p>
<pre style="margin-left: 40px;">&lt;!DOCTYPE jboss-app PUBLIC "-//JBoss//DTD J2EE Application 1.5//EN"
"http://www.jboss.org/j2ee/dtd/jboss-app_5_0.dtd"&gt;
&lt;jboss-app&gt;
&lt;module&gt;
&lt;har&gt;HibernateApplication.har&lt;/har&gt;
&lt;/module&gt;
&lt;/jboss-app&gt;</pre>
<p>While  this approach is still advisable if you want to grant backward  compatibility to your applications, with release 5.0 of the Application  Server you now have a handy quicker solution. As the new VFS of JBoss AS  is able to detect the nature of your application by scanning deployment  descriptors, it&#8217;s enough to pack your Hibernate application in a plain <strong>Java  ARchive</strong> (<strong>JAR</strong>). JBoss AS will discover the <em>.hbm.xml</em> mapping files and look for the corresponding Java classes. If  successful, the package will be deployed as a Hibernate application  straightaway.</p>
<p>The corollary of this theorem is that you can leave  out, as well, the JBoss AS configuration file <em>jboss-app.xml</em>,  which is not necessary any more. The only update required is to your <em>application.xml</em>,  where your Hibernate application is declared as a Java module in order  to make it available to other enterprise modules.</p>
<pre style="margin-left: 40px;">&lt;application&gt;
&lt;module&gt;
&lt;web&gt;
&lt;web-uri&gt;HibernateWeb.war&lt;/web-uri&gt;
&lt;context-root&gt;HibernateWeb&lt;/context-root&gt;
&lt;/web&gt;
&lt;/module&gt;
&lt;module&gt;
&lt;java&gt;HibernateProject.jar&lt;/java&gt;
&lt;/module&gt;
&lt;/application&gt;</pre>
<p>This  is how your Enterprise ARchive should look like before deploying it:</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article2-image18.png" alt="" /></p>
<p>Now  deploy your application in the usual way, by adding the project to  JBoss AS projects and then choosing <strong>Full Publish</strong>. The application  server will then produce a few log pages; if the binding of classes is  successful, you will find the following among your logs:</p>
<p><strong>16:46:18,949  INFO [HbmBinder] Mapping class: com.packtpub.hibernate.Employee  -&gt;employee<br />
16:46:19,261 INFO [HbmBinder] Mapping class:  com.packtpub.hibernate.Department -&gt; department<br />
16:46:19,277 INFO  [HbmBinder] Mapping collection:  com.packtpub.hibernate.Department.employees -&gt; employee</strong></p>
<p>In  order to test your application, simply recall your JSP default page,  using the <em>HibernateWeb</em> context. In our example:</p>
<p><em>http://localhost:8080/HibernateWeb/</em></p>
<h2>Using  the wizard to generate EJB 3</h2>
<p>Hibernate tool capabilities are not  limited to Hibernate programming. By using the reverse engineering  option, you can also generate EJB 3.0 classes in a matter of seconds.  Recall the <strong>Reverse Engineering Configuration</strong>:</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article2-image19.png" alt="" /></p>
<p>If  you Check the Generate EJB3 annotations checkbox along with Domain  code, then the outcome of your reverse engineering process would be  simple Java classes with entity annotations. That&#8217;s a huge saving of  time, especially if your database schema is rather complex. You can  still adjust your entity beans to your needs once they are generated.</p>
<h2>Hibernate  and EJB: Friends or opponents?</h2>
<p>At this stage, you might wonder  when it&#8217;s more appropriate to use EJB from your projects and when it&#8217;s  better to stay on the Hibernate framework.</p>
<p>The premise of this  debate is that EJB and Hibernate are not fully comparable because they  are semantically different. EJBs live in a container, which provides  services, such as transactions, concurrent access control, security,  instance pooling, and others. On the other hand, Hibernate is classified  as an <strong>object-relational mapping tool</strong> and it is independent from a  server container.</p>
<p>So, if comparing EJB and Hibernate is  technically a mistake, you can actually compare the <strong>Java Persistence  API</strong> and Hibernate, which are, in some ways, two <em>antagonist</em> technologies. The most important factor, which is in favor of JPA, is  that it is a standard. Using industry-standard components allows the  business vastly more flexibility when it&#8217;s necessary to change its  business model, to reorchestrate itself, and to collaborate dynamically.</p>
<p>Technically  speaking, it is also important to stress that an EJB-centric approach  is the appropriate implementation technology for two types of  applications:</p>
<ul>
<li>Applications that use distributed transactions  initiated by remote clients</li>
<li>Applications that are heavily  message-oriented and need message-driven beans</li>
</ul>
<p>On the other  hand, Hibernate framework has reached a vast community of developers and  it offers the benefit of peacefully coexisting in various deployment  environments, from application servers to standalone applications.</p>
<p>At  the end of the day, the choice between the two technologies might be to  preserve your well-tested applications backed by Hibernate Persistence  and to definitely consider switching to JPA when you are designing a new  project from the ground up. What about using them together instead?</p>
<h2>Using  Hibernate with EJB</h2>
<p>A plausible scenario is that some time ago,  you designed the persistence layer of your application with Hibernate.  Now you need to expose some functionalities of your application through  RMI or Web Services.</p>
<p>The good news is that persistent classes that  are mapped using Hibernate <em>*.hbm.xml</em> files are supported by  JBoss AS EJB 3 implementation. The EJB3 deployer will search the archive  for any <em>.hbm.xml</em> files and add them to the definition of the  underlying Hibernate <em>SessionFactory</em>. Let&#8217;s see how you can  leverage Hibernate objects from the EJB environment.</p>
<h3>Injecting  key Hibernate objects</h3>
<p>If you have been through the Hibernate web  application carefully, you might advocate that it is not a pure MVC  application, as we are accessing the persistence layer from within the  servlet.</p>
<p>This approach can be useful for a learner who wants an  easy-to-catch example of Hibernate. However, you can create a clean  separation of roles between the controller and the model tier, also by  introducing an EJB as intermediary.</p>
<p>From inside your Hibernate  project, add another stateless session bean named <em>com.packtpub.hibernate.HibernateDAOBean</em> implementing a local interface <em>com.packtpub.hibernate.HibernateDAOLocal</em>.</p>
<p>Following  is a code snippet of the bean implementing the <em>saveEmployee</em> method:</p>
<pre style="margin-left: 40px;">@Stateless
@LocalBinding(jndiBinding="HibernateDAO/local")
public class HibernateDAOBean implements HibernateDAO {
@PersistenceUnit(unitName="hibernateUnit") [1]
SessionFactory factory;
public void saveEmployee(String name,String salary,String
departmentId) {
Session hsession=null;
try {
hsession = factory.openSession();
Query query = hsession.createQuery("from Department d where
d.departmentId = :departmentId");
query.setInteger("departmentId", new Integer(departmentId));
Department dep = (Department) query.uniqueResult();
Employee emp = new Employee();
emp.setDepartment(dep);
emp.setEmployeeName(name);
emp.setEmployeeSalary(Integer.parseInt(salary));
hsession.save(emp);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new EJBException(e.getMessage());
}
finally {
if (hsession.isOpen())
hsession.close();
}
}</pre>
<p>The  most interesting point in this example is that you have injected the  Hibernate <em>SessionFactory</em> in your bean by means of the persistence  unit named <em>hibernateUnit</em>. Therefore, you have to equip your  application with a JPA <em>persistence.xml</em> file:</p>
<pre style="margin-left: 40px;">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;persistence version="1.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_1_0.xsd"&gt;
&lt;persistence-unit name="hibernateUnit" transaction-type="JTA"&gt;
&lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
&lt;jta-data-source&gt;java:/MySqlDS&lt;/jta-data-source&gt;
&lt;properties&gt;
&lt;property name="hibernate.dialect"
value="org.hibernate.dialect.MySQLDialect"/&gt;
&lt;/properties&gt;
&lt;/persistence-unit&gt;
&lt;/persistence&gt;</pre>
<p>We  leave as exercise to the reader to complete the EJB with all other  methods. On the web tier, you will do a clear cut of all the persistence  stuff, just taking care to invoke the EJB with the parameters collected  from the request. Look how simple and effective your servlet method <em>saveEmployee</em> has become:</p>
<pre style="margin-left: 40px;">@EJB(mappedName = "HibernateDAO/local")
HibernateDAO hibernateDAO;
private String saveEmployee(HttpServletRequest request) {
Session hsession=null;
String name=request.getParameter("name");
String salary=request.getParameter("salary");
String departmentId=request.getParameter("departmentId");
try {
hibernateDAO.saveEmployee(name,salary,departmentId);
}
catch (Exception e) {
e.printStackTrace();
}
return employeeList(request);
}</pre>
<p>A  snapshot of the complete Hibernate EJB-driven project follows here:</p>
<p style="text-align: center;"><img src="http://www.packtpub.com/files/images/jboss5-article2-image20.png" alt="" /></p>
<p>As  you can see, using Hibernate API works much the same way as the <em>EntityManager</em> interface. This example reveals another difference with our former web  application. Here the EJB must not attempt to manage the life cycle of  the Hibernate session; this is done internally by the EJB container,  which is in charge of commiting or rolling back the transaction,  following the EJB container&#8217;s policies.</p>
<h1>Summary</h1>
<p>Hibernate  is a flexible framework that can be used in any Java application  environment. In our excursus, we have showed how to develop a sample  application that is geared toward a managed environment. In the last two  sections of this article, we have compared the Hibernate framework with  the JPA persistence standard, showing how the two technologies can be  coupled in a single application.</p>
<img src="http://javabg.eu/?ak_action=api_record_view&id=359&type=feed" alt="" />

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://javabg.eu/2010/02/developing-applications-with-jboss-and-hibernate-part-2/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>

