@Sql 根据对象的字段查询其他信息

假设对象有属性 物料id,联系人id,可以根据这个两个 id 分别获取 描述信息,并放到Map对象中。

将多行的 union all 进行「行转列」

select 
MAX(CASE WHEN c1 = 'material_name' THEN c2 END) as 'material_name',
MAX(CASE WHEN c1 = 'contact_person' THEN c2 END) as 'contact_person'
from (
select 'material_name' c1, name c2 from mm_material where id = 725446412870901760
union all
select 'contact_person', contact_person from core_contact where id = 738365393630253056)
t

创建查询对象 GridQuery.java

@Data
@Table
public class GridQuery {

    /**
     * 必须有一个主键字段
     */
    private Long id;

    private Long materialId;

    private Long contactId;

    @Transient
    @Sql(value = "select \n" +
            "MAX(CASE WHEN c1 = 'material_name' THEN c2 END) as 'material_name',\n" +
            "MAX(CASE WHEN c1 = 'contact_person' THEN c2 END) as 'contact_person'\n" +
            "from (\n" +
            "select 'material_name' c1, name c2 from mm_material where id = :materialId\n" 
            "union all\n" +
            "select 'contact_person', contact_person from core_contact where id = :contactId)\n" +
            "t", params="materialId@materialId, contactId@contactId")
    private Map<String, Object> additionalInfo;
}

测试信息

@Autowired
private EntityDAOSupport entityDAOSupport;

@Test
public void testQuery() {
    // 单个对象
    GridQuery query = new GridQuery();

    query.setMaterialId(725446412870901760L);
    query.setContactId(738365393630253056L);

    GridQuery query1 = entityDAOSupport.query(query);

    System.out.println(query1);

    // 对象数组
    GridQuery query2 = new GridQuery();
    query2.setMaterialId(725446412870901760L);

    GridQuery query3 = new GridQuery();
    query3.setContactId(738365393630253056L);

    List<GridQuery> query4 = entityDAOSupport.query(Arrays.asList(query2, query3));
}