Soumya
Soumya

Reputation: 113

How can I map a result set to custom POJO in JPA

I need to fetch 6 columns by joining 3 different tables. I have declared them as NamedNativequery on top of the entity class and I have used create named query method form JPA. When I try fo fetch the result set i get the list of array objects instead of the List of objects of POJO type. is there any external mapping should I be defining in order to map the result set to an external POJO?

Upvotes: 2

Views: 1327

Answers (3)

tom
tom

Reputation: 1493

Building upon @khoibv's answer, you don't need the EntityManager.

import mypackage.Dto;

@Repository
@Transactional
public interface MyRepository extends CrudRepository<MyDAO, MyDAOPK> {
    @Query("""
        SELECT new mypackage.Dto(x.Field1, 
                    y.Field2, 
                    z.Field3, 
                    ...)
                 FROM XxxEntity x
                 LEFT JOIN YyyEntity y
                 LEFT JOIN ZzzEntity z
        """)
    List<Dto> find();
}

Thanks also to this answer.

Upvotes: 0

Captain
Captain

Reputation: 744

You certainly can. This should help:

@NamedNativeQuery(query = "SELECT t1.col1, t2.col2 FROM t1 JOIN t2 ON ...", name = "MyNamedQuery", resultSetMapping = "MyPojoMapper")
@SqlResultSetMapping(name = "MyPojoMapper", classes = @ConstructorResult(
    targetClass = MyPojo.class,
    columns = {
            @ColumnResult(name = "col1", type = String.class),
            @ColumnResult(name = "cols", type = String.class)
    }))

Then use it as such:

NativeQuery query = session.getNamedNativeQuery("MyNamedQuery");
MyPojo result = (MyPojo) query.getSingleResult();

Upvotes: 1

khoibv
khoibv

Reputation: 369

You can use projection to specify what properties you want to get
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

or directly get with JPQL:

Repository.java

@Repository
public class CustomRepositoryImpl {
  @Autowired
  private EntityManager entityManager;

  public List<Dto> find() {
    var query = "SELECT new Dto(
                    x.Field1, 
                    y.Field2, 
                    z.Field3, 
                    ...)
                 FROM XxxEntity x
                 LEFT JOIN YyyEntity y
                 LEFT JOIN ZzzEntity z"

    var jpqlQuery = entityManager.createQuery(query);

    return jpqlQuery.getResultList();
  }
}

Dto.java

public class Dto {

    // Must have parameterized constructor with all fields what used in Repository
    public Dto(int field1, String field2, String field3, ...) {
    }
}

Upvotes: 0

Related Questions