Kevin Sutter ha scritto:
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?
sorry for my English, you understood correctly.

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?
I am mixing, yes, but retrieve all the records is memory-consuming.
Yes, is the example from the manual, I nedd a count(*).


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)


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).

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


thank you
Edoardo

Reply via email to