0

I have a big table with ~20 fields. Can I return a List elements based on a query with let's say id, created_on, temperature without creating constructors in class T for every possible combination of fields?

Let's say something like this:

Query q = em.createQuery("SELECT id, created_on, temperature FROM Table");
result = (List<T>) q.setMaxResults(300).getResultList();

Does it work if I don't have a constructor for this specific case? Do I get a list of T objects?

  • Your best bet here might be to try to return an `Object[]` for each record, depending on the tool/framework you are using. Then, sort out in your application code which column belongs to which type. – Tim Biegeleisen Sep 30 '19 at 08:42
  • It's a strange requirement to create instances of a class with values for only a few instance members although data exists for all/most variables. I think this could lead to inconsistent data if your objects are mutable. Either create a specific class (or use a collection class) for your 3 fields or read all of them into the dedicated class. – Joakim Danielson Sep 30 '19 at 08:48

1 Answers1

0

It would be cleaner to use projections, but if you intend to have many different combinations of your 20 columns, selecting them separately gives you a return type of Object[], with column values in their respective indices.

So no, you don't get a List<T>, you get a List<Object[]>.

Kayaman
  • 72,141
  • 5
  • 83
  • 121