I am a newbie ,tried to google but I am unable to solve my query. Please help.
I am trying to map two entities : PersonA and Person in my POJO class PersonC
This post deals with the Hibernate.
The suggestion of putting the @SqlResultSetMapping and @NamedNativeQuery (or @NamedQuery) inside the @Entity class definition is not elegant and evidently does not follow the separation of concerns principle.
The more proper solution is the usage of the @MappedSuperclass annotation as the following:
SingerExtended.java (the class must be abstract):
package pl.music.model.singer.extended;
import javax.persistence.ColumnResult;
import javax.persistence.ConstructorResult;
import javax.persistence.MappedSuperclass;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.SqlResultSetMapping;
@MappedSuperclass
@SqlResultSetMapping( // @formatter:off
name = "SingerExtendedMapping",
classes = @ConstructorResult(
targetClass = SingerExtendedDTO.class,
columns = {
@ColumnResult(name = "singer_id", type = Long.class),
@ColumnResult(name = "first_name"),
@ColumnResult(name = "last_name"),
@ColumnResult(name = "count_albums", type = Long.class)
}
)
)
@NamedNativeQueries({
@NamedNativeQuery(
name = "SingerExtendedAsc",
query = "select"
+ " singer.singer_id,"
+ " singer.first_name,"
+ " singer.last_name,"
+ " (select count(*) from album where album.singer_id = singer.singer_id) as count_albums"
+ " from singer"
+ " group by singer.singer_id"
+ " order by last_name collate :collation asc, first_name collate :collation asc",
resultSetMapping = "SingerExtendedMapping"
)
}) // @formatter:on
public abstract class SingerExtended {
}
then DAO class SingerExtendedDAO.java:
package pl.music.model.singer.extended;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SingerExtendedDAO {
@PersistenceContext
EntityManager entityManager;
@Autowired
private String collation;
public List<SingerExtendedDTO> getAll(Integer page, Integer count) {
TypedQuery<SingerExtendedDTO> query = entityManager.createNamedQuery("SingerExtendedAsc", SingerExtendedDTO.class);
query.setParameter("collation", collation);
if ((count != null) && (count.intValue() > 0)) {
query.setMaxResults(count.intValue());
if ((page != null) && (page.intValue() >= 0)) {
query.setFirstResult(count.intValue() * page.intValue());
}
}
List<SingerExtendedDTO> singerExtendedDTOs = query.getResultList();
return singerExtendedDTOs;
}
}
and finally the DTO class SingerExtendedDTO.java (you must provide "full" constructor):
package pl.music.model.singer.extended;
public class SingerExtendedDTO {
private Long singerId;
private String firstName;
private String lastName;
private Long countAlbums;
// IMPORTANT: this constructor must be defined !!!
public SingerExtendedDTO(Long singerId, String firstName, String lastName, Long countAlbums) {
this.singerId = singerId;
this.firstName = firstName;
this.lastName = lastName;
this.countAlbums = countAlbums;
}
... getters & setters ...
}
If all this is put together the way presented above, we obtain a proper solution:
@SqlResultSetMapping
can be placed at any entity class (don't annotate POJOs - it won't work). Mapping to POJO class with @ConstructorResult
was added in version 2.1 of JPA. POJO used with the mapping has to have correct constructor.
All columns corresponding to arguments of the intended constructor must be specified using the columns element of the ConstructorResult annotation in the same order as that of the argument list of the constructor.
Please consult following example with query usage and work out your case accordingly.
@Entity
public class Address {
@Id int id;
String street;
}
@SqlResultSetMapping(name="PersonDTOMapping",
classes = {
@ConstructorResult(targetClass = PersonDTO.class,
columns = {@ColumnResult(name="name"), @ColumnResult(name="street")}
)}
)
@Entity
public class Person {
@Id int id;
String name;
Address address;
}
public class PersonDTO {
String name;
String street;
public PersonDTO(String name, String street) {
this.name = name;
this.street = street;
}
}
// usage
Query query = em.createNativeQuery(
"SELECT p.name AS name, a.street AS street FROM Person p, Address a WHERE p.address_id=a.id",
"PersonDTOMapping");
List<PersonDTO> result = query.getResultList();
Please note that aliases (AS name
and AS street
) has to match the names in @ColumnResult
s.
The example was tested against Ecliselink 2.5.1.
Just found a bit simpler solution using JPQL. I stole part of the example from @zbig's answer:
@Entity
public class Address {
@Id int id;
String street;
}
@Entity
public class Person {
@Id int id;
String name;
Address address;
}
public class PersonDTO {
String name;
String street;
public PersonDTO(String name, String street) {
this.name = name;
this.street = street;
}
}
List<PersonDTO> listOfPersons = em.createQuery("select new com.example.PersonDTO(p.name, a.street) " +
"from Person p, Address a " +
"WHERE p.address.id=a.id", PersonDTO.class).getResultList();
The benefit of this solution is that you don't need to use the @SqlResultSetMapping annotation, which must be placed on any entity class, not the DTO class! And that's sometimes confusing because the entity class could only be partially related (when joining multiple tables for example).
More info here