1. 程式人生 > >Mybatis查詢部分欄位

Mybatis查詢部分欄位

解決問題:資料庫表裡面很多欄位不太需要,有時只想取到裡面的部分欄位的值,如果重新定義 DTO 會比較麻煩。

BookMapper.xml 檔案中定義如下:

<!-- Book全部欄位 -->
<resultMap id="BaseResultMap" type="com.lgsc.cjbd.book.model.Book">
    <id column="book_id" property="bookId" jdbcType="BIGINT" />
    <result column="book_name" property="bookName"
jdbcType="VARCHAR" />
<result column="press" property="press" jdbcType="VARCHAR" /> <result column="author" property="author" jdbcType="VARCHAR" /> <result column="translator" property="translator" jdbcType="VARCHAR" /> <result column="isbn" property="isbn" jdbcType
="CHAR" />
</resultMap> <!-- 定義resultMap,type為HashMap --> <resultMap id="PartBookMap" type="java.util.HashMap"> <id column="book_id" property="bookId" jdbcType="BIGINT" /> <result column="book_name" property="bookName" jdbcType="VARCHAR" /> <result column
="author" property="author" jdbcType="VARCHAR" />
</resultMap> <!-- 查詢語句 --> <select id="selectPartBook" resultMap="PartBookMap"> select book_id, book_name, author from book </select>

BookMapper.java 檔案中定義如下:

List<Map<String, Object>> selectPartBook();

BookService.java 用 List< Map< String, Object > > 來接收

List<Map<String, Object>> map = bookMapper.selectPartBook();