1. 引入依賴
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>1.0.5</version>
</dependency>
2. 修改配置文件
將mapper的掃描路徑配置由mybatis改爲mybatis-plus:
mybatis:
type-aliases-package: com.szl.entity
mapper-locations: classpath:mapper/*.xml
改爲:
mybatis-plus:
type-aliases-package: com.szl.entity
mapper-locations: classpath:mapper/*.xml
3. 修改entity
@TableName("customer")
public class Customer implements Serializable{
/**
*
*/
@TableField(exist = false)
private static final long serialVersionUID = 6983500689524183915L;
@TableId
private String uuid;//主鍵
private String delFlag;//邏輯刪除標識
private String opeTime;//操作時間
private String oper;//操作人
private String createTime;//創建時間
private String customerName;//用戶名
private String email;//郵箱
private String frozenState;//凍結狀態
private String frozenType;//凍結類型
private String lastWrongLoginTime;//最後登錄錯誤時間
private Integer loginErrorTimes;//登錄錯誤次數
private String mobile;//手機號
private String password;//登錄密碼
private String salt;//密碼哈希
//getter and setter
在entity上增加註解@TableName("customer"),實體類對應的表名
主鍵上加註解:@TableId
非表字段,需要加上註解:@TableField(exist = false)
4. 修改Mapper,Service,ServiceImpl,Controller
Mapper:繼承BaseMapper<T>
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.szl.entity.Customer;
public interface CustomerMapper extends BaseMapper<Customer>{
}
Service:繼承IService<T>
package com.szl.service;
import com.baomidou.mybatisplus.service.IService;
import com.szl.entity.Customer;
public interface CustomerService extends IService<Customer>{
}
ServiceImpl:繼承ServiceImpl<BaseMapper<T>, T>
package com.szl.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.szl.entity.Customer;
import com.szl.mapper.CustomerMapper;
import com.szl.service.CustomerService;
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer>implements CustomerService{
}
修改Controller中的查詢方法,不需要在mapper.xml中寫sql,mapper,service都不用寫方法,調用mybatis-plus封裝好的方法即可。
/**
* 根據手機號查詢用戶信息
* @param mobile
* @return
*/
@RequestMapping(value = "/getCustomer", method = RequestMethod.GET)
public ResultVo getCustomer(@RequestParam(value = "mobile") String mobile){
// Customer customer = customerService.getCustomerByMobile(mobile);
EntityWrapper<Customer> entity = new EntityWrapper<Customer>();
entity.where("mobile", mobile);
List<Customer> list = customerService.selectList(entity);
return ResultVo.getData(ResultEnum.SUCCESS, list);
}
查看結果,和調用customerService.getCustomerByMobile(mobile)一致。
更多mybatis-plus用法,請參考: