当前位置: 首页 > 知识库问答 >
问题:

Hibernate ResultTransformer无法强制转换单个列

南宫博简
2023-03-14
public class SqlCount {
    private String name;
    private Double count;
    // getters, setters, constructors etc
Query hQuery = sqlQuery.setResultTransformer(Transformers.aliasToBean(SqlCount.class));
sqlQuery.addScalar("count", StandardBasicTypes.DOUBLE);

共有1个答案

白赞
2023-03-14

在hibernate中是否有某种方式可以说“自动映射所有字段。

不,查一下这里的文档,找到16.1.1。标量查询部分

最基本的SQL查询是获取标量(值)列表。

假设我们有这样的查询:

/*ORACLE SQL*/

SELECT
  SEQ                 AS "code",
  CARD_SERIAL         AS "cardSerial",
  INV_DATE            AS "date",
  PK.GET_SUM_INV(SEQ) AS "sumSfterDisc"
FROM INVOICE
ORDER BY "code";

注意:我对区分大小写的列别名使用双cote,请检查

在创建hibernate会话之后,您可以创建查询,如下所示:

/*Java*/

List<Map<String, Object>> list = session.createNativeQuery("SELECT\n" +
                    "  SEQ                 AS \"code\",\n" +
                    "  CARD_SERIAL         AS \"cardSerial\",\n" +
                    "  INV_DATE            AS \"date\",\n" +
                    "  PK.GET_SUM_INV(SEQ) AS \"sumSfterDisc\"\n" +
                    "FROM INVOICE\n" +
                    "ORDER BY \"code\"")
                    .setResultTransformer(new Trans())
                    .list();
/*Java*/

public class Trans implements ResultTransformer {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

    @Override
    public Object transformTuple(Object[] objects, String[] strings) {

        Map<String, Object> map = new LinkedHashMap<>();
        for (int i = 0; i < strings.length; i++) {

            if (objects[i] == null) {
                continue;
            }

            if (objects[i] instanceof BigDecimal) {
                map.put(strings[i], ((BigDecimal) objects[i]).longValue());
            } else if (objects[i] instanceof Timestamp) {
                map.put(strings[i], dateFormat.format(((Timestamp) objects[i])));
            } else {
                map.put(strings[i], objects[i]);
            }
        }
        return map;
    }

    @Override
    public List transformList(List list) {
        return list;
    }
}
 类似资料: