如何使用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.
您需要使用Criteria with Projections.请不要忘记指定投影别名(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中嵌套别名
选择addressDetails.countryCode作为addressDetails.countryCode
addressDetails.countryCode别名将出错.
使用本机SQL
变换器可用于具有嵌套投影的本机SQL(与HQL相对).
在这种情况下,需要使用带引号的别名:
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();
标签:java,hibernate,hibernate-criteria 来源: https://codeday.me/bug/20190918/1811199.html