Tuesday 29 May 2012

Simple Hibernate Example ..!

The files required to run the simple Hibernate Example.

1. Index.jsp
2. Web.xml
3. HibernateUtil.java
4. Person.java
5. hibernate.cfg.xml
6. Person.hbm.xml
7. server.xml

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="mypackage.*"%>
<%@ page import="org.hibernate.*"%>
<%@ page import="org.hibernate.cfg.*"%>
<HTML>
 <HEAD>
  <title>Greetings!</title>
 </HEAD>
 <BODY>
  <%
org.hibernate.Session hibernateSession = mypackage.HibernateUtil.currentSession();
Transaction tx = hibernateSession.beginTransaction();

Person person = new Person();
person.setMyName("Joe");
hibernateSession.save(person);
tx.commit();
Query query = hibernateSession.createQuery("select p from Person as p where p.myName=:name");
query.setString("name", "Joe");
for (Iterator iter = query.iterate(); iter.hasNext()  {
person = (Person) iter.next();
}
HibernateUtil.closeSession();
%>
  <br>
  <br>
  <br>
  <br>
  <table width="400" border="0" cellspacing="1" cellpadding="0"
   align="center" class="tableBox">
   <tr>
    <td CLASS="bluebanner" align="center">
     Greetings,
     <%=person.getMyName()%></TD>
   </tr>
  </table>
 </BODY>
</HTML>


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
The web.xml is:

<!DOCTYPE web-app 
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" 
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

<display-name>hibernate</display-name>

<description>hibernate</description>

<!-- Servlets -->

<!-- Servlet Mappings -->


<!-- Session Expires in 1 day --> 
<session-config>
<session-timeout>1440</session-timeout>
</session-config>

<!-- The Welcome File List -->
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>

<!-- Data Source References -->

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/hibernate</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

</web-app>

The Java source is in directory /WEB-INF/src:

package mypackage;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
// Create the SessionFactory
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.out.println("Initial SessionFactory creation failed: " + ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
}

public static final ThreadLocal hibernateSession = new ThreadLocal();

public static Session currentSession() {
Session s = (Session) hibernateSession.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
s = sessionFactory.openSession();
hibernateSession.set(s);
}
return s;
}

public static void closeSession() {
Session s = (Session) hibernateSession.get();
if (s != null)
s.close();
hibernateSession.set(null);
}
}

package mypackage;

public class Person {

private String myName;
private String id;

public String getId() {
return id;
}

private void setId(String id) {
this.id = id;
}


public String getMyName() {
return myName;
}

public void setMyName(String name) {
this.myName = name;
}
}

The hibernate.cfg.xml configuration files is:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="connection.datasource">java:comp/env/jdbc/hibernate</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Mapping files -->
<mapping resource="Person.hbm.xml"/>

</session-factory>

</hibernate-configuration>

And the Person.hbm.xml file is:

<?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="mypackage.Person" table="Person">

<!-- A 32 hex character is our surrogate key. It's automatically
generated by Hibernate with the UUID pattern. -->
<id name="id" type="string" unsaved-value="null" >
<column name="id" sql-type="char(32)" not-null="true"/>
<generator class="uuid.hex"/>
</id>

<!-- A cat has to have a name, but it shouldn' be too long. -->
<property name="myName">
<column name="name" length="80" not-null="true"/>
</property>

</class>

</hibernate-mapping>

The context xml for this example in Tomcat's server.xml is:


<Context path="/Hibernate" reloadable="true" docBase="C:\eclipse\workspace\Hibernate" workDir="C:\eclipse\workspace\hibernate\work">
<Resource name="jdbc/hibernate" scope="Shareable" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/hibernate">
<parameter>
<name>url</name>
<value>jdbc:mysql://127.0.0.1:3306/hibernate</value>
</parameter>

<parameter>
<name>maxIdle</name>
<value>2</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>2000</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>5000</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
</ResourceParams>
</Context>

Good luck!

How do we count rows using criteria in hibernate ?

We can get the rows count using the Projections. 


My code is like this: 


Criteria criteria = session.createCriteria(getReferenceClass()); criteria.setProjection(Projections.rowCount()); return ((Integer)criteria.list().get(0)).intValue();

-----------------------------------------------------------------------------------------------------------------------------------

Another solution is the following: 
1. run your criteria.list() without setting any alias => the referenced sets/list of the root entity will be filled with proxies => here you set correctly the max results and such 
2. run the alias criteria on its own in the same hibernate session => the above proxies will be initialized

something like this:


Code:
    Criteria criteria = this.getSession().createCriteria(User.class);
    criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
    criteria.setMaxResults(10);

    // First get the results without joining with the other tables
    List<User> results = criteria.list();

    // at this point the set roles is filled with proxies
    // we'll now create and execute the join so these proxies are filled since we're still in the same session
    getSession().createCriteria(User.class, "u")
            .createAlias("u.roles", "r", CriteriaSpecification.LEFT_JOIN)
            .list();

    return results;

Sunday 27 May 2012

How to convert http website into Https from java?


This topic can be a little tricky ...!

But basically there are 2 ways
1. Declarative security, in which you configure your applications web.xml and the containers' users file. Then essentially the server takes care of implementing authentication, access restriction and SSL as defined by you. This is easier but suffers from lack of portability, as the process varies for different servers.

2. Programatic security in which some or all of the security is handled by you. this is more portable but requires more work.
(OR)


To enabl SSL, you need to have an SSL certificate installed on your server (web server). There are many companies who sell these certificates at nominal rates. VeriSign is one. Once you have the certificate, install this on the server and then you must be good to go. 


 All the best...

JSP Life Cycle – explain.


JSP’s life cycle can be grouped into following phases.

1. JSP Page Translation:

A java servlet file is generated from the JSP source file. This is the first step in its tedious multiple phase life cycle. In the translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page.

2. JSP Page Compilation:

The generated java servlet file is compiled into a java servlet class.
Note: The translation of a JSP source page into its implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.

3. Class Loading:

The java servlet class that was compiled from the JSP source is loaded into the container.

4. Execution phase:

In the execution phase the container manages one or more instances of this class in response to requests and other events.
The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().

5. Initialization:

jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.

6. _jspService() execution:

This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden.

7. jspDestroy() execution:

This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.
jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.

Saturday 26 May 2012

Disable Back Button in Browser using JavaScript

Sometimes we have requirement in developing a website to disable the Back button effect from Browser. This is common in Online Banking Websites and other sites where security is of principal concern. User may hit back and navigate from the page and forget to logout.
Following are few tricks that can be used to disable the back button in browser. Please note that we do not literally “disable” the back button, but just nullify its effect is some case and hide it altogether in others.

Hence sometime it is required that we disable the functionality of Back button. But unfortunately this is not an easy task. There is no direct way of dealing with this problem. We can do few hacks to ensure that user does not get back in the browser.

Open A New Window without Back Button

This one is very crude technique. But in some case it works like charm. All you have to do is to open the webpage in a new window. This window doesn’t have back button at all because we have hide the toolbar.
This technique does work in some case but user has still a workaround to navigate to previous page. Most of the browser have options of Back in context menu. Thus user can still right click on the page and click Back to go to previous page. We will shortly see the workaround for this issue also.
Following is the code to open webpage in a new window have no toolbar (Back/Next buttons).
?
1
2
window.open ("http://enrichjava.blogspot.com/",
"mywindow","status=1,toolbar=0");
Also it is possible to disable the right click on any webpage using Javascript. Add following code in the webpage.
?
1
<body oncontextmenu="return false;">

Disable Back functionality using history.forward

This is another technique to disable the back functionality in any webpage. We can disable the back navigation by adding following code in the webpage. Now the catch here is that you have to add this code in all the pages where you want to avoid user to get back from previous page. For example user follows the navigation page1 -> page2. And you want to stop user from page2 to go back to page1. In this case all following code in page1.
?
1
2
3
4
5
6
7
<SCRIPT type="text/javascript">
    window.history.forward();
    function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
    onpageshow="if (event.persisted) noBack();" onunload="">
The above code will trigger history.forward event for page1. Thus if user presses Back button on page2, he will be sent to page1. But the history.forward code on page1 pushes the user back to page2. Thus user will not be able to go back from page1.

Related Posts Plugin for WordPress, Blogger...