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

How to transform a flat result set using 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;
}

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

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

您需要将 CriteriaProjections 一起使用。请不要忘记指定投影别名 (userName, addressDetails.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();