Tuesday, March 11, 2008

JSF : Conditional Redirect

How do you redirect based on a condition? In this case, a session variable. Example, whenever a property in the user bean is null, redirect to the login page

Solution

<jsp:scriptlet>




final javax.faces.context.FacesContext facesContext=javax.faces.context.FacesContext.getCurrentInstance();
final com.example.MyBean myBean=(com.example.MyBean)facesContext.getApplication().getVariableResolver().resolveVariable(facesContext, "myBean");
if(myBean.getProperty()==null)
{
facesContext.getExternalContext().redirect(facesContext.getExternalContext().getRequestContextPath()+"/mainmenu.faces");
}

</jsp:scriptlet>

So, put this code in a file and call this by including in whatever page you want! Simple ;)

Encode HTML code to display as HTML in your webpage

If you want do this go to the linked page. Good tool

JSTL Error : According to TLD or attribute directive in tag file, attribute value does not accept any expressions

Tried using JSTL with the JSF in my app. (My pages are HTML not XML) Tried accessing Session variables

<c:out value="${sessionScope.user.name}"></c:out>

BUT it threw me the above error. Did some searching and came up with this amendment to the taglib tag.
Instead of the standard,
<%@ taglib uri='http://java.sun.com/jstl/core'
prefix='c'%>
use the taglib,
<%@ taglib uri='http://java.sun.com/jsp/jstl/core'
prefix='c'%>
(notice the 'jsp' web folder in the URL)
This solves the problem, probably cos my pages are HTML in contrast to XML.
Go to the linked page for more details

Sunday, March 09, 2008

JPA Error : org.hibernate.HibernateException: cannot simultaneously fetch multiple bags

Apparently JPA has a problem with @OneToMany(fetch=FetchType.EAGER) relationships. Above error seems to occur whenever there is a multiple of such relationships in a class. BUT I had a problem where even a single relationship gave this error. The funny bit is that I had NO problems till I needed to add a new persistant class, thats when this guy popped up. Before that I DID HAVE MULTIPLE @OneToMany(fetch=FetchType.EAGER) relationships and it worked perfectly!

Frustrations!

Morale of the story : Don'y be lazy! Cut down @OneToMany(fetch=FetchType.EAGER) relationships. Anyways, I don't think its THAT efficient anyways

JPA Error (on delete) : java.lang.IllegalArgumentException: Removing a detached instance

This is a problem I got while deleting a record.

What I've figured is that you cannot delete a persistent object that you got very earlier (ex: as a result of a relationship of another object)

What's needed to be done is to refetch that object again by using find and delete it.

Solution:
EntityManager em=CWUtil.getEntityManager();
em.getTransaction().begin();
m=em.find(Membership.class, m.getId()); //<-Fetched again here
em.remove(m); //<-Deleted here
em.getTransaction().commit();
em.close();


Solves the problem!