Mybatis查詢多條記錄並返回List集合的方法
阿新 • • 發佈:2020-09-27
實體物件如下:
/** 使用lobmok外掛 */ @Getter @Setter @NoArgsConstructor @ToString @EqualsAndHashCode public class Vendor { private String vend_id; private String vend_name; private String vend_address; private String vend_city; private String vend_state; private String vend_zip; private String vend_country; }
XML對映檔案如下:
<select id="findVendorAll" resultType="vendor"> select * from Vendors </select>
介面檔案方法如下:
//查詢所有記錄 List<Vendor> findVendorAll();
測試檔案如下:
try { String resource = "mybatis-config.xml"; InputStream resourceAsStream = Resources.getResourceAsStream(resource); SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream,"development2"); //獲取SQLSession SqlSession openSession = build.openSession(); VendorMapper mapper = openSession.getMapper(VendorMapper.class); List<Vendors> findVendorAll = mapper.findVendorAll(); System.out.println(findVendorAll); } catch (IOException e) { System.out.println("載入配置檔案失敗"); e.printStackTrace(); }
筆記:
- XML中只需resultType屬性值為實體物件別名或全路徑名。
- mybatis會通過介面檔案的返回值型別來判斷返回的是集合還是物件。如果是物件,則按常規查詢並返回;如果是List集合,mybatis則會將查詢到的多條記錄設定進集合中並返回。
到此這篇關於Mybatis查詢多條記錄並返回List集合的方法的文章就介紹到這了,更多相關Mybatis查詢多條記錄返回List內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!