Spring Hibernate JPA 利用原生sql联表查询
测试类 代码片
.
@Test
public void getDeviceStatusList() throws Exception {
String tenantId = "1e88104b7aeab10b6debf3a73521807";
List<Object[]> list = deviceDao.getDeviceStatusList(tenantId);
// 对象类型转换
List<DeviceCustomerAttributeKvEntity> testViews = EntityUtil.castEntity(list, DeviceCustomerAttributeKvEntity.class);
for(DeviceCustomerAttributeKvEntity dca: testViews) {
System.out.println(dca.toString());
}
}
查询语句代码片
// 查询设备状态列表 Created by Wenhui Huang 2019/03/11
@Query(nativeQuery = true, value = "select d.name as deviceName, d.device_address as deviceAddress, d.device_longitude as deviceLongitude, " +
"d.device_latitude as deviceLatitude, d.created_ts as deviceCreatedTs, d.updated_ts as deviceUpdatedTs, c.title as CustomerTitle, a.bool_v as CustomerBoolV from device d " +
"left join customer c on d.customer_id = c.id " +
"left join attribute_kv a on a.entity_id = d.id and a.entity_type = 'DEVICE' " +
"where " +
"d.tenant_id = :tenantId " +
"order by d.id")
List<Object[]> getDeviceStatusList(@Param("tenantId") String tenantId);
实体转换工具类 代码片
/**
* @author Created by Wenhui
* @description 实体转换工具类
* @date 2019/3/11
*/
public class EntityUtil {
//转换实体类
public static <T> List<T> castEntity(List<Object[]> list, Class<T> clazz) throws Exception {
List<T> returnList = new ArrayList<T>();
Field[] fields = clazz.getDeclaredFields();
Object[] co = new Object[fields.length];
Class[] c2 = new Class[co.length];
//确定构造方法
for (int i = 0; i < co.length; i++) {
co[i] = fields[i].getType();
// 获取对应属性类型对应class
Class<?> classs=Class.forName(co[i].toString().substring(6, co[i].toString().length()));
c2[i] = classs;
}
for (Object[] o : list) {
Constructor<T> constructor = clazz.getConstructor(c2);
returnList.add(constructor.newInstance(o));
}
return returnList;
}
}