• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple Hibernate Example That Works

 
iarizona iarizona
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even, as a SCJA and SCJP I had to try 3 times to get Hibernate to work under Tomcat 5.0.19.

The example in the Hibernate web site is horrible, which is a shame for this emerging technology.

So I created a very simple example that works under Tomcat 5 and mySQL.

Hopefull this will help others get started.

The JSP page is named index.jsp:

<%@ 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>

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!
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now just wrap it inside the CODE tags in your post and we can read it better.

Mark
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"iArizona iArizona"-
Welcome to the JavaRanch! Please adjust your displayed name to meet the

JavaRanch Naming Policy.

You can change it

here.

Thanks! and welcome to the JavaRanch!

Mark
 
Kod Ngozo
Greenhorn
Posts: 2
Hibernate Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
iarizona iarizona wrote:Even, as a SCJA and SCJP I had to try 3 times to get Hibernate to work under Tomcat 5.0.19.

The example in the Hibernate web site is horrible, which is a shame for this emerging technology.

So I created a very simple example that works under Tomcat 5 and mySQL.

Hopefull this will help others get started.

The JSP page is named index.jsp:

<%@ 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>

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.Basic
DataSourceFactory</value>
</parameter>
</ResourceParams>
</Context>

Good luck!



Hi, i seem to struggle identifying the type of closing brace that was supposed to show where the emiticon is at. Just after the query statement and in the line where you aquire a Iterate object from.
How do i close the for statement. Please assist.

Thank you

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic