JPA默認(rèn)得查詢會把表里所有數(shù)據(jù)字段都返回
這樣會帶來一些問題
1.數(shù)據(jù)量大的字段會導(dǎo)致mysql I/O問題
2.一些敏感的信息我們不應(yīng)該直接返回給用戶蜘犁,這樣的話我們查出來數(shù)據(jù)后還得手動過濾一遍
但是JPA在這方面并沒有支持得很好皮官,而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)然我們首先要創(chuàng)建要返回數(shù)據(jù)的DTO對象
然后使用HQL語句封裝巢株。
不我們可以看看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