如何在JPA中将结果集映射到自定义POJO

时间:2019-12-14 21:57:04

标签: java spring hibernate jpa spring-data-jpa

我需要通过连接3个不同的表来获取6列。我已经在实体类的顶部将它们声明为NamedNativequery,并且使用了JPA创建命名查询方法。当我尝试获取结果集时,我得到的是数组对象列表,而不是POJO类型的对象列表。为了将结果集映射到外部POJO,我应该定义任何外部映射吗?

2 个答案:

答案 0 :(得分:1)

您当然可以。这应该有帮助:

@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)
    }))

然后按如下方式使用它:

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

答案 1 :(得分:0)

您可以使用投影来指定要获取的属性
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

或直接通过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, ...) {
    }
}