JPA 查詢(xún)部分字段

JPA默認(rèn)得查詢(xún)會(huì)把表里所有數(shù)據(jù)字段都返回
這樣會(huì)帶來(lái)一些問(wèn)題
1.數(shù)據(jù)量大的字段會(huì)導(dǎo)致mysql I/O問(wèn)題
2.一些敏感的信息我們不應(yīng)該直接返回給用戶(hù),這樣的話(huà)我們查出來(lái)數(shù)據(jù)后還得手動(dòng)過(guò)濾一遍

但是JPA在這方面并沒(méi)有支持得很好,而mybatis可以利用resultMap,resultType
那么JPA里面要怎么做呢
一種是利用jpa的@Query

@Query("SELECT new cn.hbnet.newsguess.web.dto.app.ConfigAttrDto(cf.appId,cf.attrType,cf.attrName,cf.attrValue,cf.attrDesc) FROM ConfigAttr cf WHERE  cf.attrName=?1 ")
    ConfigAttrDto findFirstByAttrNameDto(String attrName);

當(dāng)然我們首先要?jiǎng)?chuàng)建要返回?cái)?shù)據(jù)的DTO對(duì)象
然后使用HQL語(yǔ)句封裝。
不我們可以看看JPA生成的sql

Hibernate: select configattr0_.app_id as col_0_0_, configattr0_.attr_type as col_1_0_, configattr0_.attr_name as col_2_0_, configattr0_.attr_value as col_3_0_, configattr0_.attr_desc as col_4_0_ from config_attr configattr0_ where configattr0_.attr_name=?

第二種是利用entityManager

@Autowired
    private EntityManager entityManager;

public ConfigAttrDto selectByNameDto(String attrDesc){
        String sql = "SELECT app_id as appId,attr_type as attrType,attr_name as attrName," +
                "attr_value as attrValue,attr_desc as attrDesc FROM config_attr WHERE attr_name=:attrName LIMIT 1";
        Query query = entityManager.createNativeQuery(sql);
        query.setParameter("attrName",attrDesc);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(ConfigAttrDto.class));
        Object singleResult = query.getSingleResult();
        return (ConfigAttrDto)singleResult;
    }

生成的sql

Hibernate: SELECT app_id as appId,attr_type as attrType,attr_name as attrName,attr_value as attrValue,attr_desc as attrDesc FROM config_attr WHERE attr_name=? LIMIT 1
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容