好947 Mybatis 配置resultMap 帶參數查詢Map 注意selectOne資料庫返回結果一條資料庫 否則會報錯,mybatisresultmap
//TMD 寫幾個demo 還有大站採集
<a target=_blank href="http://hao947.com/" target="_blank">好947</a>
映射設定檔
<!-- type:映射實體類的資料類型 id:resultMap的唯一標識 --> <RESULTMAP id=BaseResultMap type="person"><pre name="code" class="java"><a target=_blank href="http://hao947.com/" target="_blank">好947</a>
<!-- column:庫表的欄位名 property:實體類裡的屬性名稱 --> <ID property="personId" column="person_id" /> <RESULT property="name" column="name" /> <RESULT property="gender" column="gender" /> <RESULT property="personAddr" column="person_addr" /> <RESULT property="birthday" column="birthday" /> </RESULTMAP>
映射配置查詢語句
<!-- 當查詢值得時候resultMap指定key與value。 map.put("name","專案經理") map.put("gender" 1)<pre name="code" class="java"><a target=_blank href="http://hao947.com/" target="_blank">好947</a> --> <SELECT id=selectPersonByParams resultmap="BaseResultMap" parametertype="java.util.Map"> select * from person p where p.name = #{name} and p.gender =#{gender} </SELECT>
映射管理庫表檔案
<!-- 集中管理庫表的對應檔 --><pre name="code" class="java"><a target=_blank href="http://hao947.com/" target="_blank">好947</a>
<MAPPERS> <MAPPER resource="com/hao947/sql/mapper/PersonMapper.xml" /> </MAPPERS>
測試檔案
@Test public void selectPersonByParams() { // 建立一個sqlSession <a target=_blank href="http://hao947.com" target="_blank">好947</a> SqlSession session = sqlSessionFactory.openSession(); try { Map<STRING, object=""> map = new HashMap<STRING, object="">(); map.put("name", "專案經理"); map.put("gender", 0); // 第一個參數尋找sql,規則namespace+"."+sql的id,第二個參數是sql要接收的參數 List<PERSON> list = session .selectList("com.hao947.sql.mapper.PersonMapper.selectPersonByParams",map); for (Person p : list) { System.out.println(p); } } finally { session.close(); } }
}
Mybatis 如何配置resultMap為java.util.Map類型,把值自動裝入<select id="getMapTest" resultType="map">
select id,max(columna) from tablea group by columna
</select>
樣即
MyBatis中resultMap=“Map”和resultType=“Map”區別MyBatis查詢進行select映射時候傳回型別用resultType也用resultMapresultType直接表示傳回型別而resultMap則對外部ResultMap引用resultType跟resultMap能同時存MyBatis進行查詢映射時候其實查詢出來每屬性都放對應Map裡面其鍵屬性名稱值則其對應值當提供傳回型別屬性resultType時候MyBatis會Map裡面索引值對取出賦給resultType所指定對象對應屬性所其實MyBatis每查詢映射傳回型別都ResultMap只當我們提供傳回型別屬性resultType時候MyBatis對自動給我們把對應值賦給resultType所指定對象屬性而當我們提供傳回型別resultMap時候因Map能好表示領域模型我們需要自己再進步把轉化對應對象常常複雜查詢有作用