SQLGrammarException could not fetch initial value for increment generator

In the earlier versions of Hibernate, may be hibernate 2.x, if you use increment generator on a new table then you might get this error. If you really need to use the increment generator on the new table then you need to create a dummy row on that table.
This issue is not present in the current version of hibernate i.e. Hibernate 3.x

Career 2.0: with Jared Richardson at TCJUG

      1 Comment on Career 2.0: with Jared Richardson at TCJUG

I have attended an amazing session this Monday. It was Career 2.0. talk by Jared Richardson, one of the speakers of No Fluff Just Stuff.
You can watch the video at http://qik.com/video/1009098

http://qik.com/video/1009098

The audio is not very clear. You can read Surya Suravarapu’s Blog for details.

This seminar will change the way you look at your career. (at least a bit).

HibernateSystemException- Don’t change the reference to a collection with cascade=”all-delete-orphan”

This is not an error which I got. This is an error that bugged one of my friend for a few days.

The error is

org.springframework.orm.hibernate3.HibernateSystemException: Don’t change the reference to a collection with cascade=”all-delete-orphan”: com.test.Cat.kittens; nested exception is org.hibernate.HibernateException: Don’t change the reference to a collection with cascade=”all-delete-orphan”: com.test.Cat.kittens on 10.01.2009@15.26.33

<hibernate-mapping package="com.test">
       <class name="Cat" lazy="false">
			   ......
			   ......
			   ......

               <set name="kittens" table="kitten" order-by="kitten_name asc" inverse="true"                             cascade="all-delete-orphan">
               <key column="cat_id"/>
               <one-to-many class="Kitten"/>
           </set>
       </class>
</hibernate-mapping>

We researched a few solutions on the net. The following solutions are based mainly on the two sources
http://forum.springframework.org/showthread.php?t=25809
http://www.hibernate.org/117.html#A3

Since I myself did not get this problem I can’t give much details. And the solutions below may or may not work for you.

There are two ways to solve this problem
i) If posible switch to the latest version of the Hibernate. Even though it is not a bug in the Hibernate, some people reported that somehow this problem doesn’t appear in the new version of hibernate.

Caution: If your application uses Hibernate extensively then you might consider testing the application throughly after upgrade. If you can’t upgrade for some reasons, then read on

ii) If you can’t upgrade then as per the solutions provided on the forums, you should call clear() if you need to remove the collections marked as all-delete-orphan.
Fair enough. Makes sense, since you are cascading the delete you should inform Hibernate if you intend to remove the collection.

For example,
Instead of doing something like this.

	public void removeKittens(){
	  //Load Cat with kittens
	  Cat cat = getHibernateTemplate().get(Cat.class, 1234);
	  cat.setKittens(null);
	  getHibernateTemplate().save(cat);
	}

Do something like this

	public void removeKittens(){
	  //Load Cat with kittens
	  Cat cat = getHibernateTemplate().get(Cat.class, 1234);
	  cat.getKittens.clear();
	  getHibernateTemplate().save(cat);
	}

As I said this is not a bug in Hibernate’s older version. But somehow in the new version, as people reported on the forums, this problem is not there. That means you are not required to call clear(). I am not sure because I have not faced this problem myself.

Hibernate error : org.hibernate.hql.ast.QuerySyntaxException: unexpected end of subtree

Update: Look at the comments for more information and possible solutions.

I got this error today.

Caused by: org.hibernate.hql.ast.QuerySyntaxException: unexpected end of subtree [select count(*)  from com.test.Fruits as fruit where fruit.fruitId in () order by fruit.fruitName desc ]
	at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:31)
	at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:24)
	at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:59)
	at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:235)
	at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160)
	at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
	at org.hibernate.engine.query.HQLQueryPlan.&lt;init&gt;(HQLQueryPlan.java:77)
	at org.hibernate.engine.query.HQLQueryPlan.&lt;init&gt;(HQLQueryPlan.java:56)
	at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
	at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
	at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1113)
	at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
	at com.test.FruitDAOServiceImpl.fruitCount(FruitDAOServiceImpl.java:682)
	at jrockit.reflect.VirtualNativeMethodInvoker.invoke(Ljava.lang.Object;[Ljava.lang.Object;)Ljava.lang.Object;(Unknown Source)
	at java.lang.reflect.Method.invoke(Ljava.lang.Object;[Ljava.lang.Object;I)Ljava.lang.Object;(Unknown Source)
	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:304)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:172)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:139)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107)&lt;/code&gt;

While there could be many reasons because of which this error comes. For me, the problem was that the parameter list I was passing was empty.

I was getting all the fruits for which fruit id is in the fruitIdList I was passing as the query parameter. If the fruitIdList is emply list then this problem comes. I solved it by conditionally framing query based on the list. That is instead of

public Long fruitCount(List&lt;Long&gt; fruitIdList){
	........
	Query fruitQuery = getSession().createQuery(&quot;select count(*)  from com.test.Fruits as fruit where fruit.fruitId in (:fruitIdList) order by fruit.fruitName desc &quot;);
	fruitQuery.setParameterList(&quot;fruitIdList&quot;, fruitIdList);
	List&lt;Long&gt; fruitCountList = fruitQuery.list();
	..........
}

I did this

public Long fruitCount(List&lt;Long&gt; fruitIdList){
	........
	StringBuffer queryString = new StringBuffer(&quot;select count(*)  from com.test.Fruits as fruit &quot;);

	if(fruitIdList !=null &amp;&amp; !fruitIdList.isEmpty()){
		queryString.append(&quot; where fruit.fruitId in (:fruitIdList) &quot;);
	}

	queryString.append(&quot; order by fruit.fruitName desc &quot;);

	Query fruitQuery = getSession().createQuery(queryString.toString());
	if(fruitIdList !=null &amp;&amp; !fruitIdList.isEmpty()){
		fruitQuery.setParameterList(&quot;fruitIdList&quot;, fruitIdList);
	}

	List&lt;Long&gt; fruitCountList = fruitQuery.list();
	..........
}

In short, append the collection parameter in the query and the query parameter only if the collection is non-empty.

How to configure JCaptcha with your Spring App

Update: 03/17/2009: This code example uses JCaptcha 1.0-RC6 . The latest version released on 02/04/2009 is JCaptcha 1.0. If you use JCaptcha 1.0 then you might have to make some changes to the code given in this example.

This is how I setup JCaptcha in my application. Following code snippet is for the test page I have created to test the JCaptcha and Spring integration

captchademoscreen

1) First create a controller which will generate a new Captcha for each session based on session id

Please note that your implementation can vary. The only thing you want is a simple Servlet which will execute the code in showForm method above. In my case I am relying on Spring framework to execute this code because in the JSP where you show Captcha image I have written something like this
<img id=”captchaImage” src=”http://localhost:8080/LoginApplication/captcha.htm”>. In my application the URL captcha.htm is wired to this controller. But you can choose to have a simple servlet mapped instead of a Spring Controller.

2) Make the following entries in your Spring config files to configure JCaptcha

For test purpose I have used a Simple Text Captcha.

3) To test create a command,controller and JSP like this

As you can see the JSP will just show one Captcha Image and a text box where you can enter the Image text. The controller will verify the entered text and display true or false based on the result. You can implement your logic here for the Captcha verification result.

4) Finally make the following entries in your corresponding spring config file

Oops I forgot to mention, you should have JCaptcha jars in your classpath for this example to work 😉
I have written this post using the working code I have. I might have missed some configuration in this post. Let me know if you get any error. I will update the post.

Sorting Hibernate Set using a comparator

      11 Comments on Sorting Hibernate Set using a comparator

Collection mappings in Hibernate can be configured to sort using a specific comparator.

Consider the following mapping

&lt;hibernate-mapping&gt;
&lt;class name=&quot;com.example.Person&quot; table=&quot;PERSON&quot;&gt;
......

&lt;set name=&quot;bankAccounts&quot; lazy=&quot;true&quot; cascade=&quot;all,delete-orphan&quot; inverse=&quot;true&quot; sort=&quot;natural&quot;&gt;
	&lt;key&gt;
		&lt;column name=&quot;BANK_ACCOUNT_ID&quot; precision=&quot;29&quot; scale=&quot;0&quot; not-null=&quot;true&quot; /&gt;
	&lt;/key&gt;
	&lt;one-to-many class=&quot;com.example.BankAccount&quot; /&gt;
&lt;/set&gt;

......
&lt;/class&gt;
&lt;/hibernate-mapping&gt;

In the example above Hibernate will order the bankAccounts set according to their natural order. If the BankAccout class implements Comparable interface, compareTo method will be used to sort the Set.

What if you want to sort the set differently? What if you want to use a comparator to sort the set.
The sort attribute can have three possible values

The first option is

 &lt;set name=&quot;bankAccounts&quot; lazy=&quot;true&quot; cascade=&quot;all,delete-orphan&quot; inverse=&quot;true&quot; sort=&quot;natural&quot;&gt;

which sorts by natural order

the second option is

 &lt;set name=&quot;bankAccounts&quot; lazy=&quot;true&quot; cascade=&quot;all,delete-orphan&quot; inverse=&quot;true&quot; sort=&quot;unsorted&quot;&gt;

which tells Hibernate that the Set needs not to be sorted

and the third option is

 &lt;set name=&quot;bankAccounts&quot; lazy=&quot;true&quot; cascade=&quot;all,delete-orphan&quot; inverse=&quot;true&quot; sort=&quot;comparatorClass&quot;&gt;

where you specify what comparator should be used to sort the Set.

Let’s see it through code example. For example suppose class BankAccount is defined as below

package com.example;
//import statements

public class BankAccount implements Comparable&lt;BankAccount&gt;, Serializable{

private String accountName;
private String accountShortName;
//getter and setter methods

    public int compareTo(BankAccount that) {

        final int BEFORE = -1;
        final int AFTER = 1;

        if (that == null) {
            return BEFORE;
        }

        Comparable thisAccountName = this.getAccountName();
        Comparable thatAccountName = that.getAccountName();

        if(thisAccountName == null) {
        	return AFTER;
        } else if(thatAccountName == null) {
        	return BEFORE;
        } else {
        	return thisAccountName.compareTo(thatAccountName);
        }
    }
}

In this case sort=”natural” will sort using the above compareTo method which compares the accountName to sort.
Now suppose you want that for this specific mapping you want the collection to be sorted by, say, accountShortName. You will define a Comparator like this

package com.example;
//import statements
public class BankAccountShortNameComparator implements Comparator&lt;BankAccount&gt;{
	public int compare(BankAccount o1, BankAccount o2) {
		if(o1!=null &amp;&amp; o2!=null &amp;&amp; o1.getAccountShortName()!=null &amp;&amp; o2.getAccountShortName()!=null) {
			return o1.getAccountShortName().compareTo(o2.getAccountShortName());
		}
		if(o1!=null &amp;&amp; o2!=null) {
			return o1.compareTo(o2);
		}

		return 0;
	}
}

Then your mapping will say something like this

	&lt;set name=&quot;bankAccounts&quot; lazy=&quot;true&quot; cascade=&quot;all,delete-orphan&quot; inverse=&quot;true&quot; sort=&quot;com.example.BankAccountShortNameComparator&quot;&gt;

In this way Hibernate will use your custom Comparator to sort the set

Query to find the Primary Key of a table

      No Comments on Query to find the Primary Key of a table

This is the simple query which I use to find the primary key of a table. Not a rocket science. But simple and handy.
Inner query version

SELECT TABLE_NAME, COLUMN_NAME PRIMARY_KEY,CONSTRAINT_NAME,OWNER 
FROM USER_CONS_COLUMNS UCC WHERE 
   UCC.CONSTRAINT_NAME=(
   			SELECT CONSTRAINT_NAME FROM USER_CONSTRAINTS UC WHERE UPPER(UC.TABLE_NAME)=UPPER('ADDRESS') AND UC.CONSTRAINT_TYPE='P'
   	)

Or Join Version

SELECT UCC.TABLE_NAME, UCC.COLUMN_NAME PRIMARY_KEY, UCC.CONSTRAINT_NAME,UCC.OWNER
FROM USER_CONS_COLUMNS UCC,USER_CONSTRAINTS UC
 WHERE UCC.CONSTRAINT_NAME= UC.CONSTRAINT_NAME
AND UPPER(UC.TABLE_NAME)=UPPER('ADDRESS')
AND UC.CONSTRAINT_TYPE='P'

where ‘ADDRESS’ is the name of the table

Problem- java.lang.NoClassDefFoundError: javax/el/ValueExpression Tomcat

Problem- java.lang.NoClassDefFoundError: javax/el/ValueExpression

Possibly
you are using different set of jars at runtime and compile time. In
case of tomcat you might be using some of the jars. Try adding jars
like el-api.jar, javaee.jar, jstl-1.2.jar from your development
environment to the Tomcat/common/lib folder, one by one and it should
solve the problem

Powered by ScribeFire.

org.hibernate.TransientObjectException Revisited

This is continuation of my earlier post on org.hibernate.TransientObjectException. Let me write the scenario again

<class name=”com.xxx.A” table=”A” schema=”TESTSCHEMA”>
<id name=”aId” type=”java.lang.Long”>
<column name=”A_ID” precision=”29″ scale=”0″ />
</id>

…………………..
some more mapping elements
…………………..
…………………..
<many-to-one name=”bId” class=”com.xxx.B” fetch=”select”>
<column name=”B_ID” precision=”29″ scale=”0″ />
</many-to-one>

…………………..

A is referring to B using a primary key column of bId of B.

In that post I have mentioned that if B is a transient object and you don’t want to persist the value of B to A then just tell the hibernate to ignore that value by saying
update=”false” insert=”false” in the many to one mapping.

But what if you want to persist the value of foreign key in A.

Then the approach is different. You have to make sure that instance B is persistent not transient.

That is if your code says something like

A a = new A();
B b = new B();
a.setB(b);
…..
…..

session.save(a);

you are in trouble. Because B is in transient state. You have to attach b to the session.
There may be other ways of attaching this transient object to session. The approach I am following is simple. I am reading the value of B from the database using Hibernate. That way, hibernate attaches B to session and it is then a persistent object.

That is I do something like

A a = new A();
B b = session.get(B.class, new Long(1));
a.setB(b);
…..
…..

session.save(a);

I won’t get any exception because this time there is no transient object to save. All the objects are persistent.

Powered by ScribeFire.