第一步:引入mybatis依賴
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>
第二步:類目表實體類
package com.payease.dataobject; import lombok.Data; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * 類目 * Created by liuxiaoming * 2017-11-09 */ @Entity @DynamicUpdate //動態時間修改 @Data // get set toString 登方法 public class ProductCategory { /** 類目id. */ @Id @GeneratedValue private Integer categoryId; /** 類目名字. */ private String categoryName; /** 類目編號. */ private Integer categoryType; // private Date createTime; // // private Date updateTime; public ProductCategory() { } public ProductCategory(String categoryName, Integer categoryType) { this.categoryName = categoryName; this.categoryType = categoryType; } }
第三步:編寫相應的mapper文件
package com.payease.dataobject.mapper; import com.payease.dataobject.ProductCategory; import org.apache.ibatis.annotations.*; import java.util.List; import java.util.Map; /** * @Created By liuxiaoming * @CreateTime 2017/12/12 下午6:13 **/ public interface ProductCategoryMapper { /** * 通過參數為map保存 * @param map * @return */ @Insert("insert into product_category(category_name, category_type) values (#{category_name , jdbcType=VARCHAR}, #{category_type, jdbcType=INTEGER})") int insertByMap(Map<String, Object> map); /** * 通過參數為對象保存 * @param productCategory * @return */ @Insert("insert into product_category(category_name, category_type) values (#{categoryName , jdbcType=VARCHAR}, #{categoryType, jdbcType=INTEGER})") int insertByObject(ProductCategory productCategory); /** * 查單一數據 * 通過categoryType查詢product_category表 @Result注解設置返回值 * @param categoryType * @return */ @Select("select * from product_category where category_type = #{categoryType}") @Results({ @Result(column = "category_id", property = "categoryId"), @Result(column = "category_name", property = "categoryName"), @Result(column = "category_type", property = "categoryType") }) ProductCategory findByCategoryType(Integer categoryType); /** * 查集合 * 通過categoryName查詢product_category表 @Result注解設置返回值 * @param categoryName * @return */ @Select("select * from product_category where category_name = #{categoryName}") @Results({ @Result(column = "category_id", property = "categoryId"), @Result(column = "category_name", property = "categoryName"), @Result(column = "category_type", property = "categoryType") }) List<ProductCategory> findByCategoryName(String categoryName); /** * 根據某個字段更新 * 通過查詢category_type 來修改 category_name * @param categoryName * @param categoryType * @return */ @Update("update product_category set category_name = #{categoryName} where category_type = #{categoryType}") int updateByCategoryType(@Param("categoryName") String categoryName, @Param("categoryType") Integer categoryType); /** * 根據對象更新 * 通過查詢category_type 來修改 category_name * @param productCategory * @return */ @Update("update product_category set category_name = #{categorName} where category_type = #{categoryType}") int updateByObject(ProductCategory productCategory); /** * 根據某個字段來刪除數據 * 通過category_type 來刪除數據 * @param categoryType * @return */ @Delete("delete from product_category where category_type = #{categoryType}") int deleteByCategoryType(Integer categoryType); /** * mybatis xml的使用樣例 * 通過categoryType 查詢數據 * @param categoryType * @return */ ProductCategory selectByCategoryType(Integer categoryType); }
第四步:測試類的編寫
package com.payease.dataobject.mapper; import com.payease.dataobject.ProductCategory; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Created By liuxiaoming * @CreateTime 2017/12/12 下午6:19 **/ @RunWith(SpringRunner.class) @SpringBootTest public class ProductCategoryMapperTest { @Autowired private ProductCategoryMapper mapper; @Test public void insertByMap() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("category_name","吃雞專屬"); map.put("category_type",103); int result = mapper.insertByMap(map); Assert.assertEquals(1,result); } @Test public void insertByObject() throws Exception { ProductCategory productCategory = new ProductCategory(); productCategory.setCategoryName("大吉大利"); productCategory.setCategoryType(102); int result = mapper.insertByObject(productCategory); Assert.assertEquals(1,result); } @Test public void findByCategoryType() throws Exception{ ProductCategory result = mapper.findByCategoryType(102); Assert.assertNotNull(result); } @Test public void findByCategoryName() throws Exception{ List<ProductCategory> result = mapper.findByCategoryName("吃雞專屬"); Assert.assertNotEquals(0,result.size()); } @Test public void updateByCategoryType(){ int result = mapper.updateByCategoryType("絕地求生", 103); Assert.assertEquals(1, result); } @Test public void updateByObject(){ ProductCategory productCategory = new ProductCategory(); productCategory.setCategoryName("今晚吃雞|大吉大利"); productCategory.setCategoryType(102); int result = mapper.updateByObject(productCategory); Assert.assertEquals(1, result); } @Test public void deleteByCategoryType(){ int result = mapper.deleteByCategoryType(102); Assert.assertEquals(1, result); } @Test public void selectByCategoryType(){ ProductCategory result = mapper.selectByCategoryType(101); Assert.assertNotNull(result); } }
第五步:啟動類上加入mapper掃描注解
package com.payease; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan(basePackages = "com.payease.dataobject.mapper") public class SellApplication { public static void main(String[] args) { SpringApplication.run(SellApplication.class, args); } }
第六步:對於mybatis xml文件的使用需要
1.在 resource/mapper文件夾下創建相應的xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.payease.dataobject.mapper.ProductCategoryMapper" > <resultMap id="BaseResultMap" type="com.payease.dataobject.ProductCategory" > <id column="category_id" property="categoryId" jdbcType="INTEGER" /> <result column="category_name" property="categoryName" jdbcType="VARCHAR" /> <result column="category_type" property="categoryType" jdbcType="INTEGER" /> <result column="create_time" property="createTime" jdbcType="TIMESTAMP" /> <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" /> </resultMap> <sql id="base_column" > category_id,category_name,category_type </sql> <select id="selectByCategoryType" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="base_column" /> from product_category where category_type = #{category_type,jdbcType=INTEGER} </select> </mapper>
2.在application.yml文件夾下配置xml文件的掃描
注1: mapper文件的使用 封裝到dao層
package com.payease.dataobject.dao; import com.payease.dataobject.mapper.ProductCategoryMapper; import org.springframework.beans.factory.annotation.Autowired; import java.util.Map; /** * @Created By liuxiaoming * @CreateTime 2017/12/13 下午3:23 **/ public class ProductCategoryDao { @Autowired ProductCategoryMapper mapper; public int insertByMap(Map<String, Object> map){ return mapper.insertByMap(map); } }
注2:日志查看mapper文件中的SQL語句
這是application.yml文件的配置
spring: datasource: driver-class-name: com.mysql.jdbc.Driver username: root password: liuxiaoming_123 #1234 url: jdbc:mysql://rm-uf6qe0894f7hv8977o.mysql.rds.aliyuncs.com/sell?characterEncoding=utf-8&useSSL=false #url: jdbc:mysql://127.0.0.1/sell?characterEncoding=utf-8&useSSL=false jpa: show-sql: true jackson: default-property-inclusion: non_null redis: host: 192.168.1.183 port: 6379 server: context-path: /sell #logging: # pattern: # console: "%d - %msg%n" #日志格式 日期 - 信息 空格 # path: /Users/liuxiaoming/Documents/ideawork/sell_log #日志路徑 默認名字spring.log # file: /Users/liuxiaoming/Documents/ideawork/sell_log/sell.log #日志文件+路徑 # level: #日志級別 # com.payease.LoggerTest: debug #日志級別指定某個類 也可以步制定類 直接在level: 后面配置 #日志查看SQL語句 logging: level: com.payease.dataobject.mapper: trace wechat: mpAppId: wxd898fcb01713c658 mpAppSecret: 47ccc303338cee6e62894fxxxxxxxxxxx openAppId: wx6ad144e54af67d87 openAppSecret: 91a2ff6d38a2bbccfb7e9f9079108e2e mchId: 1483469312 mchKey: 06C56A89949D617xxxxxxxxxxx keyPath: /var/weixin_cert/h5.p12 notifyUrl: http://sell.natapp4.cc/sell/pay/notify templateId: orderStatus: e-Cqq67QxD6YNI41iRiqawEYdFavW_7pc7LyEMb-yeQ #projectUrl: # wechatMpAuthorize: http://sell.natapp4.cc # wechatOpenAuthorize: http://sell.natapp4.cc # sell: http://sell.natapp4.cc projectUrl: wechatMpAuthorize: http://127.0.0.1:8080 wechatOpenAuthorize: http://127.0.0.1:8080 sell: http://127.0.0.1:8080