mybatis的通用mapper的通用Example使用

來源:互聯網
上載者:User

mybatis的通用mapper的通用Example使用,當然也有不對應通用mapper的普通Example使用

想要偷懶不寫mybatis裡的一大堆mapper.xml檔案,就想使用通用的Mapper類減少工作量。

    首先,我使用的是Maven項目,所以匯入Mapper的Maven依賴

  [html]  view plain  copy   <dependency>     <groupId>tk.mybatis</groupId>     <artifactId>mapper</artifactId>     <version>3.2.0</version>   </dependency>    

    同時有一項必要依賴項:項目依賴於JPA的註解,需要添加Maven依賴: [html]  view plain  copy   <dependency>     <groupId>javax.persistence</groupId>     <artifactId>persistence-api</artifactId>     <version>1.0</version>   </dependency>  

    接下來,在設定檔applicationContext.xml中配置Mapper [html]  view plain  copy   <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">       <property name="basePackage" value="com.isscas.ucqcs.common.dao"/>       <property name="properties">           <value>               mappers=tk.mybatis.mapper.common.Mapper      //這是Mapper介面配置,當介面為此預設配置時,可不寫           </value>       </property>   </bean>  

    直接將MyBatis的配置 org 修改為 tk 即可 [html]  view plain  copy   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  

    到這裡,Mapper的配置已經全部完成。

 

    只要在自己的Mapper介面上繼承Mapper<T>介面,即可調用通用Mapper類中全部的方法。

    另外要注意的是:該Mapper類對實體類有自己的解析方式  :  表名和欄位名會預設使用類名,駝峰轉底線(即UserNamed對應表名/欄位名user_name),使用@Column(name = "真實名稱")可以指定表名/欄位名。

    另,需要@Id標記主鍵欄位,對不需要的欄位,可用@Tranisent忽略

    Mapper介面中包含單表的增刪改查分頁功能。

    下面給出一個查詢執行個體: [html]  view plain  copy   CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);   //查詢全部   List<Country> countryList = mapper.select(new Country());   //總數      //通用Example查詢   Example example = new Example(Country.class);   example.createCriteria().andGreaterThan("id", 100);//這裡給出的條件查詢為id>100   countryList = mapper.selectByExample(example);  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.