TechnoBuzz

A Techno Blog, mainly about Java

Exception Scenarios

Its been a while since I chimed in on the topic of Exceptions:

Checked : (java.lang.Exception). This type of exception represents useful information about the operation of a legally specified request that the caller may have had no control over and that the caller needs to be informed about. With checked exceptions, Java language forces us to document all the anticipated ways in which control might exit a method:

Unchecked : (java.lang.RuntimeException). These are exceptions that occur as a result of programming errors that the program could not be expected to catch.

Now, it is time to talk about the Exception Handling capabilities with DAOs in the Spring Framework

(2.5)

SQL Exception Translatorsql exception can be translated to a DataAccessException using the translate method

ex1, ex2, ex3 , ex4

The method HibernateDaoSupport :: convertHibernateAccessException – convert the given HibernateException to an appropriate exception from the org.springframework.dao hierarchy.

SessionFactoryUtils : 
public static DataAccessException convertHibernateAccessException(HibernateException ex) {
		if (ex instanceof JDBCConnectionException) {
			return new DataAccessResourceFailureException(ex.getMessage(), ex);
		}
		if (ex instanceof SQLGrammarException) {
			return new InvalidDataAccessResourceUsageException(ex.getMessage(), ex);
		}
		if (ex instanceof DataException) {
			return new InvalidDataAccessResourceUsageException(ex.getMessage(), ex);
		}
		if (ex instanceof LockAcquisitionException) {
			return new CannotAcquireLockException(ex.getMessage(), ex);
		}
		if (ex instanceof ConstraintViolationException) {
			return new DataIntegrityViolationException(ex.getMessage(), ex);
		}
		if (ex instanceof JDBCException) {
			return new HibernateJdbcException((JDBCException) ex);
		}
		if (ex instanceof PropertyValueException) {
			return new DataIntegrityViolationException(ex.getMessage(), ex);
		}
		if (ex instanceof PersistentObjectException) {
			return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
		}
		if (ex instanceof TransientObjectException) {
			return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
		}
		if (ex instanceof ObjectDeletedException) {
			return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
		}
		if (ex instanceof QueryException) {
			return new HibernateQueryException((QueryException) ex);
		}
		if (ex instanceof UnresolvableObjectException) {
			return new HibernateObjectRetrievalFailureException((UnresolvableObjectException) ex);
		}
		if (ex instanceof WrongClassException) {
			return new HibernateObjectRetrievalFailureException((WrongClassException) ex);
		}
		if (ex instanceof NonUniqueResultException) {
			return new IncorrectResultSizeDataAccessException(ex.getMessage(), 1);
		}
		if (ex instanceof StaleObjectStateException) {
			return new HibernateOptimisticLockingFailureException((StaleObjectStateException) ex);
		}
		if (ex instanceof StaleStateException) {
			return new HibernateOptimisticLockingFailureException((StaleStateException) ex);
		}

		// fallback
		return new HibernateSystemException(ex);
	}

Hibernate Template

Advertisements

September 13, 2008 Posted by | Hibernate & ORM, J2EE, Open Source | 1 Comment

JPA Examples

jpa spec jsr 317

open jpa manual

In an applicationserver, EntityManager instances are typically injected, rendering the EntityManagerFactory unnecessary.

javax.persistence:

  • Persistence : contains static helper methods to obtain EntityManagerFactory
    instances in a vendor-neutral fashion.
  • EntityManagerFactory: is a factory for Entity-Manager
  • EntityManager: is the primary JPA interface used by applications.Each EntityManager manages a set of persistent objects, and has APIs to insert new objects and delete existing ones. EntityManagers also act as factories for Query instances.
  • Entity: persistent objects that represent datastore records.
  • Query: Query interface is implemented by each JPA vendor to find persistent objects that
    meet certain criteria. JPA standardizes support for queries using both the Java Persistence Query Language (JPQL) and the Structured Query Language (SQL). You obtain Query instances from an EntityManager.

JPA uses a version field in your entities to detect concurrent modifications to the same datastore record. When the JPA runtime detects an attempt to concurrently modify the same record, it throws an exception to the transaction attempting to commit last. This prevents overwriting the previous commit with stale data.

private int version;

JPA introduces another form of object identity, called entity identity or persistent identity. Entity identity tests whether two persistent objects represent the same state in the datastore.

May 11, 2008 Posted by | Hibernate & ORM, J2EE | Leave a comment

Roller n Struts2

Just noticed that Dave Johnson has upgraded Roller in version 4.o to use Struts2 and OpenJPA.

After learning about Webwork last year, I played with using Struts2 examples in a 1.4.x environment.

Roller wiki

Install Guide

November 18, 2007 Posted by | Blogging, Hibernate & ORM, Struts | 1 Comment

Seam

I couple months ago I heard the podcast with Gavin King about Seam. I came across this blog posting talking about Seam. I do see alot more people using EJBs than what was done in the past now that with JPA and IoC all in one. I do not see Spring going away though.

May 28, 2006 Posted by | Hibernate & ORM, IoC, Spring | Leave a comment

Native SQL in Hibernate3

         StringBuffer sql = new StringBuffer();
        sql.append("select david.field1 as myfield1, david.field2 as myfield2 drom david.table1");          
        SQLQuery sqlQuery = getSession().createSQLQuery(sql.toString());
        sqlQuery.addScalar("myfield1", Hibernate.TIMESTAMP);
        sqlQuery.addScalar("myfield2", Hibernate.INTEGER);
        List results = sqlQuery.list();

       

March 21, 2006 Posted by | Hibernate & ORM | Leave a comment

Feedbacks

Seems Hibernate has this system of feedback or credits. We’ll see how good it works.

don’t use Class.forName(REG_FILE);

Use
Thread.currentThread().getContextClassLoader().getResourceAsStream(REG_FILE)

March 16, 2006 Posted by | Hibernate & ORM | Leave a comment

JPA

Solormetric , is now part of BEA and has open sourced the code.

Its now being used as part of the Open JPA.

March 15, 2006 Posted by | Hibernate & ORM | Leave a comment

Combo Meal: Hibernate 3 with Derby

I have been getting familiar with the Derby  open source database  which was contributed by IBM (Cloudscape).

As a learning exercise, I decided to integrate the use of Derby in sampling Hibernate 3.

I have read parts of Pro Hibernate 3 and Hibernate Quickly. I liked both books, but I think the Manning book was more what I was looking for. I needed a book that covered the X-Doclet with Hibernate 3.

Hibernate3 needed from what i can tell these Jars: cglib-2.1.3, dom4j-1.6.1, ehcache-1.1, hibernate3, jta, asm

I start off using an ANT build file schema-export target to invoke the schema generator:

<target name="schema-export">
    <taskdef name="schemaexport"
             classname="org.hibernate.tool.hbm2ddl.SchemaExportTask">
         <classpath refid="runtime.classpath"/>
    </taskdef>
     <schemaexport
         config="${src.java.dir}/hibernate.cfg.xml"
         quiet="no"
         text="no"
         drop="no"
         delimiter=";"
         output="${build.classes.dir}/schema-export.sql">
     </schemaexport>
    </target>

My hibernate property values to use Derby as the database looked like this (note: you can also specify these values in the hibernate config xml file):

hibernate.dialect=org.hibernate.dialect.DerbyDialect
hibernate.connection.driver_class=com.ibm.db2.jcc.DB2Driver
hibernate.connection.username=user1
hibernate.connection.password=user1
hibernate.connection.url=jdbc:derby:net://localhost:1527/test;create=true

Connecting to the derby database:

ij> connect ‘jdbc:derby:net://localhost:1527/test’ user ‘user1’ password ‘user1’;

ij> select tablename from sys.systables where tabletype = ‘T’;

I did not do the upgrade, but this was helpfull.

January 8, 2006 Posted by | Hibernate & ORM | Leave a comment

A Hibernate 3 experience

This blog entry has the Hibernate founders tuning in about one guys experience. They seem a little sensitive on what is just some constructive feedback.

January 3, 2006 Posted by | Hibernate & ORM | Leave a comment

Hibernate 3

This entry will mark my start at looking at hibernate 3. It appears the transition path is from using the xdoclet to using annotations in documenting the mappings.

It appears there is a toolset within hibernate 3 worth trying out : "We have made significant improvements to the Hibernate toolset for Hibernate3. This is however work in progress and we’ll continue to implement new ideas and features as the third generation of the Hibernate3 object persistence stack evolves. " Others

Q&A with Gavin

Tips

Raible Designs talks about Pagination with Hibernate: "Hibernate 3 has added the ability of adding projections like count(*) w/ aliases to the Query"

Pagination

December 30, 2005 Posted by | Hibernate & ORM | Leave a comment

Data Access Object

Link: Dazed & Confused.

October 2, 2005 Posted by | Hibernate & ORM | Leave a comment

Dyna Forms

Denver Java Users Group has a talk on Dynamic Struts Forms.

I noticed they have a nice ppt presentation on Spring/Hibernate.

August 8, 2005 Posted by | Hibernate & ORM, IoC, Struts | Leave a comment

J2EE Programming Forums – General: 20 Sites for Java Developers

Link: Javalobby – Java J2EE Programming Forums – General: 20 Sites for Java Developers.

Rod Johnson on Persistence

August 5, 2005 Posted by | Hibernate & ORM | 1 Comment

To Persist

Persistence paper

July 26, 2005 Posted by | Hibernate & ORM | Leave a comment

apache iBATIS

iBATIS   apache. comprised of two main products – DAO and SQLMaps.  The DAO  provides an excellent way of abstracting the persistence layer while the SQLMaps provides your basic Object/Relational Mapping functionality.

[articles] [FAQ] [mail archives]

[java developer guide pdf]  [generic developer guide] [tutorial]

[dao developer guide]

a blog  Vinny blog    ibatis with struts

http://del.icio.us/tag/ibatis

July 15, 2005 Posted by | Hibernate & ORM | 8 Comments

Persistence Choice Factors

"The choice of Java persistence technology is not simply a technical decision. Project managers need to also consider some non-technical factors: " [more…]

July 8, 2005 Posted by | Hibernate & ORM | Leave a comment

Some examples

Road to hibernate

http://jroller.com/page/prokhorenko/20050629

lead me to here.

June 30, 2005 Posted by | Hibernate & ORM, IoC | Leave a comment

TriJug Meeting with Gavin King

I attended the TriJug meeting with Gavin King of JBoss.  Gavin is one of the founders of the Hibernate (Object/Relational Technology). He is also co-author of the book Hibernate in Action which covers version 2.0. 

Just a few notes from the meeting:

Hibernate 3 is the recent version. Supports annotation to document O/R mapping, allthough you can still use XML to indicate this.

There was a question from audience asking about a situation where they had their database in production in one schema, and the same database for design in another schema. Gavin was like I don’t see why you would want to do that.

He indicated that hibernate would still be a good fit for applications that did alot of joins, but as always you are limited by the speed of the database.

I asked him if Hibernate would be enhanced to support JDO. He indicated NO. He basically said that they are against the JDO spec. That was the main thing I wanted to get answered at this meeting as JDO and Hibernate seem similar. But, Hibernate is strictly a O/R implementation where as the JDO implemntations follow Sun’s specification.

As far as JBoss, Mark Fleury has had a busy week, and he talks about Gluecode here.  His point in the blog entry about Open Source model being validated now that IBM has bought this technology is true. But, this was already the case as IBM’s Portal product is built ontop of the Jetspeed  open source product. 

May 17, 2005 Posted by | Hibernate & ORM, Open Source | Leave a comment

A Hibernate Experience

Reflections on Hibernate:

"with hql and its other mechanisms of querying a database (e.g. the criteria api), hibernate has successfully taken root and i believe is on its way to supplanting sql"

May 6, 2005 Posted by | Hibernate & ORM | Leave a comment

Toplink

Ive used hibernate, never have used Toplink.

January 13, 2005 Posted by | Hibernate & ORM, JDO | Leave a comment

From EJB to Hibernate to EJB3

Link: Real Player Presentation.

December 17, 2004 Posted by | Hibernate & ORM | Leave a comment

Get started with Hibernate

I have avoided the book Hibernate in action so far. But, here is an aricle on getting started with Hibernate.

October 26, 2004 Posted by | Hibernate & ORM | Leave a comment

Hibernate with WAS

I did Hibernate with WAS and DB2 here. I will have to see how dead on I was now with this article from IBM

September 19, 2004 Posted by | Hibernate & ORM | Leave a comment

Java Tutorials

Struts,JSTL,Hibernate

Exadel Java Topics

JDO, Struts, Java 1.5 etc.

September 1, 2004 Posted by | Hibernate & ORM, J2EE, JDO, Struts | Leave a comment

Hibernate

Based on the hibernate.org example application, I came up with a servlet that writes to a db2 database. This uses the hibernate.properties file to specify the jdbc connection. I still would like to try getting the connection information using a JNDI context like is described here.

jars (place in build path):
cglib-full-2.0.1.jar
commons-logging-2.1.jar
hibernate2.jar
jta.jar
odmg-3.0.jar
commons-collections-1.0.3.jar
dom4j-1.4.jar
jdbc2_0-stdext.jar
log4j-1.2.8.jar

hibernate.properties:
hibernate.connection.driver_class = com.ibm.db2.jcc.DB2Driver
hibernate.connection.url = jdbc:db2://ipaddress:portnum/qms
hibernate.connection.username =
hibernate.connection.password =

Users.hbm.xml:
<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD//EN”
http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd”&gt;
<hibernate-mapping>
<class name=”Users” table=”QMS.USERS”>
<id name=”name” type=”string” column=”NAME”> <generator class=”assigned”/> </id> 
<property name=”type” type=”integer” column=”TYPE”/>
</class>
</hibernate-mapping>

hibernate.cfg.xml:
<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 2.0//EN”
http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd”&gt;
<hibernate-configuration>
<session-factory>
<property name=”hibernate.connection.driver_class”>com.ibm.db2.jcc.DB2Driver
</property>
<property name=”hibernate.connection.url”>jdbc:db2://ipaddress:portnum/qms
</property>
<property name=”hibernate.connection.username”>db2inst1</property>
<property name=”hibernate.connection.password”></property>
<property name=”dialect”>net.sf.hibernate.dialect.DB2Dialect</property>
<property name=”show_sql”>true</property>
<property name=”transaction.factory_class”>
net.sf.hibernate.transaction.JDBCTransactionFactory</property>
<property name=”hibernate.cache.provider_class”>
net.sf.hibernate.cache.HashtableCacheProvider</property>
<property name=”hibernate.hbm2ddl.auto”>update</property>
<mapping resource=”Users.hbm.xml”/>
</session-factory>
</hibernate-configuration>

Database table:

CREATE TABLE qms.users ( 
NAME VARCHAR(32 ) NOT NULL PRIMARY KEY 
,TYPE INTEGER
) ;


public class Users 

   private String name; 
   private int type;
   public int getType() {
return type;

   public String getName() {
return name;

   public void setType(int type) {
this.type = type;

   public void setName(String i) {
name = i;
}
 }


import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import net.sf.hibernate.Hibernate;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.Query;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.cfg.Configuration;
public class AdminServlet extends HttpServlet {
SessionFactory _sessions;


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.println("<head>”);
    pw.println(“<meta http-equiv=\”Content-Type\” content=\”text/html;
charset=ISO-8859-1\">");
    pw.println("<title>Hibernate example</title>”);
    pw.println("</head>”);
    pw.println();
    pw.println("<body>”);
    pw.println();
    pw.println("<h1>Hibernate example</h1>”);
    pw.println();
    try {
            int i =
do_hibernate();
    } catch (HibernateException e) {
           e.printStackTrace();
    }
}
public void configure() throws HibernateException {
_sessions = new Configuration()
.addClass(Users.class)
.buildSessionFactory();
}
public int do_hibernate() throws HibernateException {
    System.out.println("start");
    configure()
    Session session = _sessions.openSession();
    Transaction tx = null;
    try {
           tx = session.beginTransaction();
           Users u = new Users();
           u.setName("jay@aol.com");
          u.setType(1);
          session.save(u);
          tx.commit();
    } catch (HibernateException e) {
        e.printStackTrace();
    }
    return 0;
}
}

Hibernate API
Hibernate Guide
Mapping
Object to Relational Mapping and Relationships mapping using hibernate
Just looking for some examples on hibernate.
The first example comes from Aaron Johnson

with DB2

properties file

A new book is out called Hibernate – A developers notebook

A blog In relation to…

The Kickstart Guide

Mike Gloegl

Learn Hibernate

Developer Works

and of course Hibernate.org
hibernatedownload

wiki

plugin

Hibernate Sync plugin. To install, go to the install/update perspective , right click, new, enter url of
http://www.binamics.com/hibernatesync/eclipse2.1/site.xml, then on lower panel go down 3 levels,
and single click the item, on right side should see a button thats says install. I did this with wsad 5.1.2.

This article mentions the plugin.

Hibernate with xdoclet tutorial.

July 9, 2004 Posted by | Hibernate & ORM | Leave a comment