一尘不染

如何使用Hibernate转换平面结果集

hibernate

是否可以将SQL结果映射到非平面对象?

List<Customer> customers = hibernateSession().createCriteria(CustomerDetailsView.class)
                .add(Restrictions.in("userName", userName))
                .setProjection(buildProjection())
                .setResultTransformer(Transformers.aliasToBean(Customer.class))
                .list();

在我的情况下, CustomerDetailsView 具有扁平结构。但是我需要将其映射到这样的对象:

public class Customer {
    private String userName;
    private String title;
    private String firstName;
    private String lastName;
    private String type;
    private String companyName;
    private AddressDetails addressDetails;
}

public class AddressDetails {
    private String countryCode;
    private String addressLine1;
    private String zipOrPostCode;
    private String city;
    private String countryDivisionName;
    private String countryDivisionCode;
    private String countryDivisionTypeCode;
    private String residentialAddress;
}

阅读 184

收藏
2020-06-20

共1个答案

一尘不染

是的,有可能。您可以为其使用自定义转换器:
FluentHibernateResultTransformer

您可以复制粘贴代码,也可以通过Maven添加jar:fluent-hibernate-
core

您需要使用CriteriaProjections。请不要忘记指定投影别名(userNameaddressDetails.countryCode

Criteria criteria = session.createCriteria(Customer.class);
criteria.createAlias("addressDetails", "addressDetails", JoinType.LEFT_OUTER_JOIN);

criteria.setProjection(Projections.projectionList()
        .add(Projections.property("userName").as("userName"))
        .add(Projections.property("addressDetails.countryCode")
        .as("addressDetails.countryCode")));

List<Customer> customers = criteria.setResultTransformer(
        new FluentHibernateResultTransformer(Customer.class)).list();

与HQL一起使用

无法将其与HQL一起使用,因为Hibernate不允许在HQL中使用嵌套别名

select addressDetails.countryCode as addressDetails.countryCode

addressDetails.countryCode别名会出错。

与本机SQL一起使用

该转换器可用于带有嵌套投影(与HQL相反)的本机SQL。在这种情况下,需要使用带引号的别名:

String sql = "select c.f_user_name as userName, d.f_country_code as \"addressDetails.countryCode\" "
        + "from customers c left outer join address_details d on c.fk_details = d.f_pid";

List<Customer> customers = session.createSQLQuery(sql)
        .setResultTransformer(new FluentHibernateResultTransformer(Customer.class))
        .list();
2020-06-20