将值映射到实体

时间:2019-06-07 08:09:06

标签: java jpa spring-data-jpa

我想在使用SQL JOIN执行SQL查询之后实现DTO映射:

查询:

public List<Businesses> findCompaniesBusinessesById(Integer id) {
    String hql = "SELECT bus FROM " + Businesses.class.getName() + " bus " 
                + " INNER JOIN " + Companies.class.getName() + " comp "
                + " ON comp.id = bus.company_id " 
                + " WHERE bus.business_owner_id = :id "
                + " AND bus.business_owner_type = 'Merchant' "
                + " ORDER BY bus.id ASC";
    TypedQuery<Businesses> query = entityManager.createQuery(hql, Businesses.class).setParameter("id", id);
    List<Businesses> businesses = query.getResultList();
    return businesses;
}

实体公司:

@Entity
@Table(name = "companies")
public class Companies implements Serializable {

    @Id
    @Column(name = "id", unique = true, updatable = false, nullable = false)
    private int id;

    @Column(length = 255)
    private String name;

    @Column
    @Convert(converter = LocalDateTimeConverter.class)
    private LocalDateTime created_at;

    @Column
    @Convert(converter = LocalDateTimeConverter.class)
    private LocalDateTime updated_at;
    ...
}

实体企业:

@Entity
@Table(name = "businesses")
public class Businesses {

    @Id
    @Column(name = "id", unique = true, updatable = false, nullable = false)
    private int id;

    @Column(length = 4)
    private Integer business_owner_id;

    @Column(length = 255)
    private String business_owner_type;

    @Column(length = 4)
    private Integer company_id;

    @Column
    @Convert(converter = LocalDateTimeConverter.class)
    private LocalDateTime created_at;

    @Column
    @Convert(converter = LocalDateTimeConverter.class)
    private LocalDateTime updated_at;
    .......
}

!注意!。在“企业”实体中,设计时没有属性name

DTO:

public class BusinessesDTO {

    private Integer id;

    private String name;

    ....... 
}

!注意!在BusinessesDTO中,我们期望name是设计好的,并且我们希望对其进行映射。

DTO映射:

@Mapper(config = BaseMapperConfig.class)
public interface BusinessesMapper {

    BusinessesDTO toDTO(Businesses company);
    .....
}

手动执行查询时的查询结果:

SELECT * FROM  businesses bus   
        INNER JOIN  companies comp
          ON comp.id = bus.company_id 
          WHERE bus.business_owner_id = 1
          AND bus.business_owner_type = 'Merchant' 
          ORDER BY bus.id ASC

enter image description here

您会看到有一个列名。

我试图使用此代码来获取映射:

@Autowired
private BusinessesMapper businesses_mapper;

List<BusinessesDTO> list = null;
try {
    list = StreamSupport.stream(merchantService.findCompaniesBusinessesById(id).spliterator(), false)
        .map(businesses_mapper::toDTO)
        .collect(Collectors.toList());
} catch (Exception e) {
    e.printStackTrace();
}

String joinedList = list.stream()
    .map(BusinessesDTO::getName)
    .collect(Collectors.joining(", "));

但是结果是我得到了NULL。由于某些原因,名称未正确映射,我找不到原因。

是否可能不具有name属性到Businesses实体中,并使用DTO将存在于SQL查询中的name字段映射。

从SQL查询图片中,我可以正确地获得名称,如上面所示。你能告诉我我哪里错了吗?

0 个答案:

没有答案