My Finder query is extremly slow. After reviewing the Log files, it appears that the Bean is making an initial query to the database and then a separate query for each subsequent rows. Is there any way to get the Collection at once?

Nick Maiorano

Congratulations! You've just described the infamous n+1 entity bean problem. Let me explain what's happening.

First, your application container is querying the database and retrieving the keys to all of the rows that match the WHERE clause. Second, for each matching row, it is taking an entity bean instance from the pool and assigning the key to it. When you call the getXXX() on the entity bean, the entity bean is fetching all the field values from the row it represents. So if your query found 15 rows, the "n" value is 15 and represents the getXXX() methods you will call on your 15 entity beans. The +1 is the initial query on the database. You will have a total of 16 database dips.

By now, you're probably disgusted with entity beans. However, consider this: entity beans cut down the amount of code dramatically. You avoid having to write JDBC (except in special cases) and reduce the amount of bugs you generate. I'm not trying to over dramatize this but our team just spent days fixing tons of JDBC code which had no close statements on result sets and JDBC connections. This caused our application to crash.

Some application containers have something called field groups which allow you to group fields together. If, for example, you have a field named XXX in the same group as the key field, calling getXXX() on the entity bean will avoid a second database dip because XXX will have already been read in with the initial query.