openjpa-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Kevin Sutter <kwsut...@gmail.com>
Subject Re: how to count sub-elements without retrieving them?
Date Wed, 25 Mar 2009 13:26:01 GMT
Edoardo,
If I understand your desired scenario, you are hoping to define a "smart"
getCounter() on your Entity that can count the number of Subs without
actually retrieving and generating the complete List from the database.  Is
that what you are trying to do?

That might be easier said than done.  You are mixing business logic with
your data model.  I would think that sticking with a Query of some kind
would be the better way to go.  The example you cited below mentions the MAX
aggregate function, but wouldn't you be more interested in the COUNT
function?

Maybe what you should consider is defining a NamedQuery in your Entity class
and then reference that for performing the desired "getCounter" behavior.
You would still need access to your EM, but you need that anyway for any of
these JPA-related operations, don't you?  How are you maintaining your
EntityManager/PersistenceContext?

Let's start with that before diving in too deep...

Kevin

On Wed, Mar 25, 2009 at 2:04 AM, Edoardo Panfili <edoardo@aspix.it> wrote:

> Hi,
> I have an object that use a one-to many relation
> --------------------------------
> @OneToMany(cascade={CascadeType.ALL}, mappedBy="segnalazione",
> fetch=FetchType.LAZY)
> public List<Sub> getSub() { return sub; }
> public void setSub(List<Sub> sub) { this.sub = sub;}
>
> @Transient
> public int getCounter() {
>   return this.getSub().size();
> }
> --------------------------------
>
> sometimes I need to know only the number of Sub but getCounter() retrieve
> from DB a lot of not useful data.
>
> I found this fragment of code in openJpa manual
> --------------------------------
> EntityManager em = ...
> Query q = em.createQuery("SELECT MAX(x.price) FROM Magazine x WHERE x.title
> = 'JDJ'");
> Number result = (Number) q.getSingleResult();
> --------------------------------
>
> This is usefull in a java program but I need to use the counter in a JSP (a
> servlet retrieves the data and a JSP write a summary of data retrieved whit
> the counter), It is more useful to me to use a property of my object (like
> getCounter() ).
>
> I can't figure how to write it, can someone help me?
>
> thank you
> Edoardo
>
>

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message