Fetch Id only in a JPA TupleQuery

Isn`t it possible too fetch only the id from a foreign object.

Simple example:

class Person {
   int id;
   String name;
   @JoinColumn(name = "ADDRESS_ID", referencedColumnName = "ID")
   @ManyToOne(fetch = FetchType.LAZY)
   Address addressesId
}

class Address {
  int id;
  String city;
}

CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Tuple> q = criteriaBuilder.createTupleQuery();
Root<Person> from = q.from(Person.class);
q.multiselect(from.get(Person_.name),
              from.get(Person_.AdresseId);
TypedQuery<Tuple> query = em.createQuery(q);
List<Tuple> resultList = query.getResultList();

I need only the ID from Address which is of course present in Person table, but JPA generate automatically an inner join query and entities with a null Address are omitted. The join is unnecessary. Is there a way to only fetch the id from Address in this TupleQuery?

Xanas

Answers


JPA can only use the mappings provided to return data, and since the address foreign key within Person is mapped using an object reference mapping, any inclusion of it in queries requires a join in JPA. The only way to get nulls included would be to use a left outer join as Koitoer describes below.

The alternative though is to create another read-only basic mapping for the addressId foreign key within the Person entity.

class Person {
   int id;
   String name;
   @JoinColumn(name = "ADDRESS_ID", referencedColumnName = "ID")
   @ManyToOne(fetch = FetchType.LAZY)
   Address address;
   @Column(name ="ADDRESS_ID", insertable=false, updatable=false)
   private Long addressId;
}

This would allow you to use the 'address' attribute when you want an Address object instance, and the 'addressId' in queries when you only need the foriegn key value and not a full Address entity:

CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Tuple> q = criteriaBuilder.createTupleQuery();
Root<Person> from = q.from(Person.class);
q.multiselect(from.get(Person_.name),
              from.get(Person_.AddressId);
TypedQuery<Tuple> query = em.createQuery(q);
List<Tuple> resultList = query.getResultList();

would return the name and addressId value from the Person table without any joins.


Need Your Help

Running parallel test in Local Machine

java internet-explorer selenium webdriver

I have some selenium tests. Those are code with the base of selenium API version 2.33. Those are running in my Windows 7 machine with IE7(9 compatible mode ). I just want to run them in parallel in...