As was said, a Tuple
is an ordered list of things. It helps to understand why you would use such a thing. Consider that you have a table in the database and for whatever reason you only want to select some of the columns from that table. From such a query you can get Objects and Tuples. Example, consider an Entity that has two fields, latitude
and longitude
:
@Entity
public class User {
@Id @GeneratedValue private Long id;
private BigDecimal latitude;
private BigDecimal longitude;
When you want to query only the latitude and longitude columns, where do you put the results? One of the ways to do it is to use Tuples
:
// With objects, the alias information is lost.
List<Object[]> s = em.createQuery("select u.lattitude as lattitude, u.longitude as longitude from User u", Object[].class).getResultList();
s.stream().forEach((record) -> {
System.out.println(record[0]+","+record[1]);
});
// With Tuples, the alias information is retained.
List<Tuple> t = em.createQuery("select u.lattitude as lattitude, u.longitude as longitude from User u", Tuple.class).getResultList();
t.stream().forEach((record) -> {
System.out.println( record.get("lattitude") +","+record.get("longitude"));
});
As you can see, Tuples
have an alias
property that gets filled out by the query, which you can then use later. This is more convenient than an Object
. Also, TupleElement
supports Java Generics, so you can also have more type safety than you can have with Objects
.