Edoardo,

On Wed, Mar 25, 2009 at 10:20 AM, Edoardo Panfili <edoa...@aspix.it> wrote:

> Kevin Sutter ha scritto:
>
>> 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?
>>
> I am writing by myself persistence.xml (no automatic tools)


What I meant is how are you maintaining the lifecycle of the EntityManager?
Are you using application-managed persistence and creating your own EMF and
associated EM's?  Where are you doing this logic?


>
>
>
> my solution (not so beautiful) based on your post
> -------------------------------------------
> @Entity
> @NamedQueries({
> @NamedQuery(name="counter",
> query="SELECT COUNT(x) FROM SubObject x WHERE x.mainObject.idMainObject =
> ?1")
> })
> public class MainObject {
>    [.....]
>    private int count;
>    @Transient
>    public int getCount() { return count; }
>    public void setCount(int count) { this.count =count; }
>
> }
> -------------------------------------------
>
> And during object retrieve
> -------------------------------------------
> public class find extends HttpServlet{
>
> public void doPost(HttpServletRequest req, HttpServletResponse res){
> [.....]
> queryString = "SELECT * FROM MainObject WHERE ........";
> Query query = entityManager.createNativeQuery(queryString,
> MainObject.class);
> lista = query.getResultList();
> Query q = entityManager.createNamedQuery("counter");
> for(Object o: lista){
>    MainObject k = ((MainObject)o);
>    q.setParameter(1, k.getIdMainObject());
>    Number result = (Number) q.getSingleResult();
>    k.setOoo(result.intValue());
> }
> [.....]
> }
>
> }
> -------------------------------------------
>
> Now my application uses less memory, is faster (but less clean as you say).


Cool.  So, we're making progress...  Tell me this, what would your doPost
method look like if you had your way?  It looks confusing to do the native
query just to get the set of MainObject id's and then rifle through the
named query invocations to count the number of SubObjects.  I'm trying to
figure out what your intended usage is.  And, I'm trying to figure out how
you are separating your data model from your business logic.


>
> Can I map a method of my "MainObject" to a specific query? something like
> namedQuery but at method level.


No.  The idea of named query is to be available for any usage of that
Entity.  It's not meant to be fired due to a method request.  Although the
idea sounds interesting...  :-)


Thanks,
Kevin


>
>
>
> thank you
> Edoardo
>
>

Reply via email to