Showing posts with label hibernate. Show all posts
Showing posts with label hibernate. Show all posts

Monday, December 22, 2008

Hibernate/JPA objects in an HTTP session

Last week I ran into an unexpected problem.  

My application has a User object, which contains various fields.  User also has a JPA-managed One-To-Many relationship with something called Store.  This relationship had been working fine (and in fact through this story never stopped working).

For the first time, last week, I added a JPA-managed relationship between User and an entity class called QuickListEntry.  QuickListEntry in turn has a relationship with Product, which in turn has plenty of other relationships with other entities.

We're using Struts 2, which is only marginally relevant here.

In Action A, we load up the User object from the SecurityContext, do some stuff with him, and then stuff him into the Session for access later.  In Action B, we pull him out of the session and read his data, including his QuickListEntries.  Well what do you know -- I'm getting a Hibernate LazyInitializationException.  This has never happened before.  It never happed with the User's Stores.  What's going on?

Well here's what's going on.  When the User is stuffed into the Session, he is disconnected from the JPA EntityManager.  When he is pulled out of the Session, his extended relationships (User to QuickListEntry to Product) can't be followed, because he is disconnected from the EntityManager.  

So the most correct solution in this case is not to stuff the User object into the Session at all.  Either stuff the userid in there (which is probably harmless) and then use the userid to re-load the User from the DB in every Action's prepare() method; or pull the User from the SecurityContext on every page load (again, I'd put this in the prepare() method of every Action class).

Friday, March 21, 2008

Hibernate Session vs. EntityManager

The answer to the question below is depressingly easy. I was overthinking the problem. Session is Hibernate's custom implementation; EntityManager is the standard JPA creature. If you want to stick to the standards (in this case, I do, although the odds of our shifting to a different JPA provider are very slender), stick to EntityManager. The big thing I'm missing out on so far is access to Hibernate's various CascadeTypes; the JPA default CascadeTypes are rather limited.

Monday, March 17, 2008

Open Hibernate Question

Open question: I see in the Hibernate documentation that Hibernate's EntityManager is "similar to" Hibernate's Session interface. But it isn't clear when I should be using one versus the other. I'm using the EntityManager now and everything's going fine. But I want to make sure I'm doing this The Right Way so that I don't have to rip it apart and rewrite it in three months when I better understand the business problems I'm fighting. Any readers have any insight?

Thursday, February 14, 2008

Glad to see this works

I wasn't sure this would work. One quick unit test verifies that it does. Very good to know:

Query query = getEntityManager().createQuery("from User order by ?");
query.setParameter(1, "lastName");


I don't know why it wouldn't work, really, but I had only used replaceable parameters in the WHERE clause of queries before.

Friday, February 1, 2008

Well that was funny

I only had to change the URLs in hibernate.cfg.xml and in applicationContext.xml. That's good and easy.

Things didn't work for a sec, because in the 'real' database that I'm now using, Users aren't stored in a 'user' table, they are stored in, let's say, a table called 'bogus_user'. With Hibernate 2 I would have known to go into User.hbm.xml and modify the table name reference, but the current quickstart project uses Hibernate 3 annotations. I checked the docs quickly, suspecting I need to change the @Entity annotation on the User class. The docs pointed me at the free Chapter 2 sample of the Manning Java Persistence with Hibernate book. It showed that I needed to add @Table(name="bogus_user") to the User class declaration. I did that, and redeployed.

This time I ran into a hilarious error. The bogus_user table has thousands of entries, and my simpleminded script was trying to display all of them at once. So -- next step -- limit the number of entries returned. That will be after lunch, as my wife and I are going to meet for lunch for the first time in ages.

I'll probably be buying that Manning book this weekend.

Thursday, January 31, 2008

Onward

The rest of the quickstart demo went pretty smoothly. Not surprising, considering that it was largely a matter of typing (or copy and pasting) sample code into real files.

But now the fun begins: problems. The truth is that you don't understand how a technology or combination of technologies works until you've had to fix them when they're supposed to work.

So, first problem: Exception stack trace in my Tomcat log. I am not going to drop the entire stack trace into the blog at this point, but let me describe how I'm handling this. First, I skimmed the stack trace looking for references to code that I know to be mine. In this case there are no "quickstart." files anywhere in the stack trace, so I know it's not my Java code. Now, here are the first few lines of the stack trace:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.lang.NoSuchMethodError: org.springframework.beans.factory.xml.ParserContext.registerBeanComponent(Lorg/springframework/beans/factory/parsing/BeanComponentDefinition;)V
Caused by: java.lang.NoSuchMethodError: org.springframework.beans.factory.xml.ParserContext.registerBeanComponent(Lorg/springframework/beans/factory/parsing/BeanComponentDefinition;)V
at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser$AopAutoProxyConfigurer.configureAutoProxyCreator(AnnotationDrivenBeanDefinitionParser.java:130)
at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser.parse(AnnotationDrivenBeanDefinitionParser.java:79)

The most obvious problem appears to be an error parsing applicationContext.xml. Probably I have a typo in there somewhere. However, I can't find one after glancing over the file for five minutes and that is almost certainly enough time for now. So I'm going to do something annoying. I typed this one in by hand and probably fat-fingered something. So I'm going to copy-and-paste the file contents from the demo and see if that makes the problem go away. If it doesn't then I'll have to use my brain and nobody wants that.

That doesn't make the problem go away! Crap. Time to do some Google searches on the exception messages.

And Matt Raible comes through again. Dude is rapidly becoming my hero. A thread on the AppFuse mailing list suggests that there might be collisions between various Spring jars. I'm reorganizing my build path, let's see how this works.

...nope. OK, time to review my build path, make sure I have everything I need. Yes, this would have been a good time to have used Maven, I know.

Hey, it turns out that I ignored a bunch of Hibernate jars earlier -- specifically the Hibernate Annotations and Hibernate Entity Manager jars. I'll grab them now. And that doesn't solve the problem either. Same error.

Clean, refresh, delete the deployment, rebuild, redeploy... and it's a whole new suite of errors! But these are more comprehensible. They can go in another post.

Adding jars to the project

It just occurred to me that if you have this feed copied to your livejournal friends list you're going to hate me, because there's no way that I know of to hide crap behind a cut. So, er, sorry. But this is mostly for my future reference, and so being spammy is good from my perspective. And maybe if somebody else needs a hand in the future they might find these posts and get something good out of them.

So, I made a 'quickstart' project in MyEclipse, and added it to the deployments listed under my Tomcat 6 server in the 'servers' tab.

Now it's time to download and add 24 jar files to my project. Although MyEclipse 6 doesn't support Struts 2 yet, I'm going to try and handle the Hibernate jars with MyEclipse's "add Hibernate capabilities" feature, let's see how this goes. I need the Hibernate Core, Hibernate Annotations, and Hibernate Entity Manager features, 16 jars in all.

This guide says I need antlr.jar, asm.jar, asm-attrs.jar, cglib.jar, dom4j.jar, jdbc2_0-stdext.jar, ehcache.jar, hibernate3.jar, xml-apis.jar, and commons-collections.jar from the Hibernate Core. MyEclipse provides all of these in the Hibernate 3.1 Core Libraries module; it also adds commons-logging, jaas, jaxen beta (I have no idea what jaxen is), jta, log4j, and xerces.

The quickstart guide says that Hibernate Annotations should provide ejb3-persistence.jar, jta.jar, and hibernate-annotations.jar. MyEclipse's Hibernate Core gives jta.jar. The other two aren't provided by MyEclipse, so I will need to grab them.

The quickstart guide says that "Hibernate Entity Manager" should provide
hibernate-entitymanager.jar, javassist.jar, and jboss-archive-browsing.jar. MyEclipse's library plugin does not provide any of these, so I'll have to go grab them as well. No problem.

For now I'll add the Hibernate 3.1 Core library to my project, and go out and get the other Hibernate libraries that I need. I'll take the defaults for the Hibernate config file (putting it in src/hibernate.cfg.xml) because I don't have strong opinions about where it belongs.

Hm. After another page of the wizard, the wizard is now asking me about creating Hibernate SessionFactory classes and stuff. I'd better check the quickstart to see if it's got suggestions as to how I should set that junk up.

After reviewing the quickstart, I'm going to hold off on having a wizard-created SessionFactory. I can always create one later if I need it.

OK, that's done. Now I notice the quickstart has references to spring.jar. I could probably just enable the Spring capabilities within MyEclipse. MyEclipse's Spring 2.0 Core libraries includes a lot of stuff that I may not need. If I were working with a team I would probably hold off for the time being, but since it's just me and I'm confident that I know what's in all these jars, I'll add them all wizardishly too.

By default MyEclipse wants Spring's applicationContext.xml in "src". I know I don't want it there; the quickstart wants it in WebRoot/WEB-INF/ and I am inclined to agree, so off it goes. Also, I'm not going to create a Spring LocalSessionFactory, because the quickstart appears to be doing things differently.

Wednesday, January 30, 2008

Good intro -- Struts 2 + Hibernate

Another good link, something to look at from work: Struts + Spring + JPA (Hibernate).