Question

I'm working with Java Apache Cayenne, under a MySQL DB. I have quite a large table with a single bigint PK and some fields. I'd like to retrieve just only the PK values and not all the object that maps this entity, as it would be too resource-consuming.

Is there a snippet that I can use, instead of this one that retrieves all the objects?

    ObjectContext context = ... 
    SelectQuery select = new SelectQuery(MyClass.class);
    List<MyClass> result = context.performQuery(select);
Était-ce utile?

La solution

You should try using SQLTemplate instead of SelectQuery. Here's a quick example:

ObjectContext context = ... 
SQLTemplate select = new SQLTemplate(MyClass.class, "SELECT #result('PK_COLUMN' 'long') FROM MY_TABLE");
List result = context.performQuery(select);

You can find more information here

Autres conseils

+1 for Josemando's answer. And here is another way that may work in case you are planning to only work with a subset of fetched objects:

ObjectContext context = ... 
SelectQuery select = new SelectQuery(MyClass.class);

select.setPageSize(100);

List<MyClass> result = context.performQuery(select);

'setPageSize' ensures that 'result' only contains ids, until you attempt to read an object from the list. And when you do, it will resolve it page-by-page (100 objects at a time in the example above). This may fit a number of scenarios. Of course if you iterate through the entire list, eventually all objects will be fully resolved, and there will be no memory benefit.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top