1

我有一个包含 2 个实体类数据的本地查询的情况,如何通过 @SqlResultSetMapping 将该数据映射到实体类? 例如

Native query:- select customer.name, address.area from customer, address where customer.id=address.custid;

2 实体类,如客户和地址,名称作为客户中的变量,区域作为地址实体类中的变量。

Customer class:
@Entity
public class Customer {
    @Id
    private String name;
    getters and setters
.....
.....
.....
}

Address Class entity:
@Entity
public class Address{
    @Id
    private String area;
    getters and setters
.....
.....
.....
}

要将本机查询与实体类映射,可以通过在实体中提供 @SqlResultSetMapping 并在 nativeQuery 中提供映射名称来完成

Query query = entityManager.createNativeQuery(sbQuery, "checkInfoMapping");

它将检查映射名称并映射到相应的实体类,这可以针对单个实体类完成。

如果我有来自 2 个实体类的本机查询的数据,是否可以完成,如果是,我如何使用本机查询将其映射到实体类?

4

2 回答 2

1

你应该这样做:

@SqlResultSetMapping(
   name = "checkInfoMapping",
   classes = {
      @ConstructorResult(targetClass = ResultInfo.class,
         columns = {
            @ColumnResult(name = "cust_name", type = String.class),
            @ColumnResult(name = "adr_area", type = String.class)
         }
      )
   }
)
@Entity
@Table(name = "TST_CUSTOMER")
public class Customer {

    @Id
    @Column(name = "cust_id")
    private Long id;

    @Column(name = "cust_name")
    private String name;

    ...
}


@Entity
@Table(name = "TST_ADDRESS")
public class Address{

    @Column(name = "adr_area")
    private String area;

    @ManyToOne
    @JoinColumn(name = "adr_cust_id")
    private Customer customer;
    ...
}

// this is not entity, just dto class
public class ResultInfo
{
   private String name;
   private String area;

   public ResultInfo(String name, String area)
   {
      this.name = name;
      this.area = area;
   }
   // ...
}

和查询:

List<ResultInfo> resultList = entityManager.createNativeQuery(
   "select cust_name, adr_area from TST_CUSTOMER, TST_ADDRESS where TST_CUSTOMER.cust_id = TST_ADDRESS.adr_cust_id",
   "checkInfoMapping")
   .getResultList();
于 2020-02-14T09:03:29.560 回答
0

最简单的方法是在您的本机查询中使用 JOIN,如下所示。

Native query :- select c.name,a.area from customer c JOIN address a ON c.id = a.custid

因此,您必须只提供客户实体的结果集映射。

于 2020-02-14T09:19:21.037 回答