简体   繁体   English

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

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

I need to fetch 6 columns by joining 3 different tables.我需要通过加入 3 个不同的表来获取 6 列。 I have declared them as NamedNativequery on top of the entity class and I have used create named query method form JPA.我已经在实体类的顶部将它们声明为 NamedNativequery,并且我使用了创建命名查询方法表单 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.当我尝试获取结果集时,我得到的是数组对象列表,而不是 POJO 类型的对象列表。 is there any external mapping should I be defining in order to map the result set to an external POJO?为了将结果集映射到外部 POJO,是否应该定义任何外部映射?

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();

You can use projection to specify what properties you want to get您可以使用投影来指定要获取的属性
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

or directly get with JPQL:或直接使用 JPQL 获取:

Repository.java存储库.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, ...) {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM