0

续。在jpa 本机查询上检索多个实体

  • 我的数据库(测试)
    在此处输入图像描述

    company - ID {PK}, name
    staff - ID{PK}, name, companyID{FK}
    department - ID{PK}, name, companyID{FK}, staffID{FK}
    project - ID{PK}, name, staffID{FK}
    
  • 首先,我要备份company表。

    String query = "SELECT c.ID as companyid, c.name as companyname FROM company c";
    Query q = em.createNativeQuery(query, "MAPPING");
    List<CompanyDTO> list = q.getResultList();
    
    Company.java
    @SqlResultSetMapping(name = "MAPPING", classes = {
    @ConstructorResult(
        targetClass = CompanyDTO.class,
        columns = {
            @ColumnResult(name = "companyid"),
            @ColumnResult(name = "companyname")
        })
    })
    ...
    
  • 其次,我要备份staff表。

    String query = "SELECT s.ID as staffid, s.name as staffname, s.companyID as companyID 
                    FROM staff s JOIN company c ON c.ID = s.companyID";
    Query q = em.createNativeQuery(query, "MAPPING");
    List<CompanyDTO> list = q.getResultList();
    
    Company.java
    @SqlResultSetMapping(name = "MAPPING", classes = {
    @ConstructorResult(
        targetClass = CompanyDTO.class,
        columns = {
            @ColumnResult(name = "staffid"),
            @ColumnResult(name = "staffname"),
            @ColumnResult(name = "companyID")
        })
    })
    ...
    
  • 现在我不想修理我的桌子和班级。我该如何控制?从以下?

    SELECT ... FROM ? 
    List<?> list = q.getResultList();
    

    任何帮助请...

4

0 回答 0