MyBatis-Plus?UserMpper接口示例實現(xiàn)
UserMapper 接口示例
在 MyBatis-Plus 中,UserMapper 是一個非常簡單但功能強大的接口。它通常長這樣:
基本結(jié)構(gòu)
package com.example.mapper; // 根據(jù)你的項目結(jié)構(gòu)調(diào)整包名
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.User; // 你的User實體類所在的包
import org.apache.ibatis.annotations.Mapper;
// 使用@Mapper注解讓Spring管理這個接口,并生成實現(xiàn)類
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 不需要寫任何方法,就已經(jīng)繼承了BaseMapper中的所有CRUD方法
// 但你也可以根據(jù)需要添加自定義方法
}
詳細解釋
1. 必需的組成部分
繼承 BaseMapper<T>:這是最關鍵的部分,通過繼承并指定泛型類型為你的實體類(這里是 User),你的 UserMapper 就自動獲得了 BaseMapper 中定義的約 20 個常用 CRUD 方法。
@Mapper 注解:這個注解告訴 MyBatis 這是一個映射器接口,Spring 啟動時會自動為其創(chuàng)建代理實現(xiàn)類。
2. 完整的示例(包含實體類和配置)
為了讓示例更完整,這里也展示一下相關的 User 實體類和 Spring Boot 配置:
User 實體類 (User.java)
package com.example.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
// 指定實體類對應的數(shù)據(jù)庫表名
@TableName("user")
public class User {
// 主鍵字段
@TableId
private Long id;
// 普通字段,如果字段名與數(shù)據(jù)庫列名一致,可以不加注解
private String name;
private Integer age;
// 如果數(shù)據(jù)庫列名與字段名不一致,可以使用@TableField指定
@TableField("email_address")
private String email;
// 省略構(gòu)造函數(shù)、getter和setter方法...
public User() {
}
public User(Long id, String name, Integer age, String email) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
}
// getter 和 setter 方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 其他getter和setter...
}
Spring Boot 配置 (application.yml)
# 數(shù)據(jù)源配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: your_username
password: your_password
# MyBatis-Plus 配置
mybatis-plus:
mapper-locations: classpath*:mapper/**/*.xml # 如果有自定義XML查詢文件,指定路徑
type-aliases-package: com.example.entity # 實體類包路徑
configuration:
map-underscore-to-camel-case: true # 自動開啟駝峰命名轉(zhuǎn)換
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印SQL日志
3. 如何使用 UserMapper
在你的 Service 或 Controller 中,你可以直接注入 UserMapper 并使用它:
package com.example.service;
import com.example.mapper.UserMapper;
import com.example.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> getAllUsers() {
// 查詢所有用戶
return userMapper.selectList(null);
}
public User getUserById(Long id) {
// 根據(jù)ID查詢用戶
return userMapper.selectById(id);
}
public List<User> getUsersByName(String name) {
// 條件查詢:使用Lambda表達式避免硬編碼字段名
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.like(User::getName, name);
return userMapper.selectList(wrapper);
}
public int addUser(User user) {
// 插入用戶
return userMapper.insert(user);
}
public int updateUser(User user) {
// 更新用戶
return userMapper.updateById(user);
}
public int deleteUser(Long id) {
// 刪除用戶
return userMapper.deleteById(id);
}
}
4. 自定義方法
雖然 BaseMapper 提供了豐富的通用方法,但有時你可能需要添加自定義查詢:
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 自定義查詢方法:查詢年齡大于指定值的用戶
@Select("SELECT * FROM user WHERE age > #{minAge}")
List<User> selectUsersOlderThan(@Param("minAge") Integer minAge);
// 或者使用XML配置的方式
List<User> selectUsersByComplexCondition(Map<String, Object> params);
}
然后在 resources/mapper/UserMapper.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.example.mapper.UserMapper">
<select id="selectUsersByComplexCondition" resultType="com.example.entity.User">
SELECT * FROM user
WHERE name LIKE CONCAT('%', #{name}, '%')
AND age BETWEEN #{minAge} AND #{maxAge}
</select>
</mapper>
總結(jié)
UserMapper 接口的核心特點是:
- 繼承
BaseMapper<User>,自動獲得大量CRUD方法 - 使用
@Mapper注解標記為MyBatis映射器 - 不需要編寫任何實現(xiàn)代碼,MyBatis-Plus會自動生成代理實現(xiàn)
- 可以添加自定義方法滿足特定業(yè)務需求
這種設計極大地減少了傳統(tǒng)MyBatis中需要編寫的模板代碼,讓開發(fā)者能夠更專注于業(yè)務邏輯的實現(xiàn)。
到此這篇關于MyBatis-Plus UserMpper接口示例的文章就介紹到這了,更多相關MyBatis-Plus UserMpper接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
如何使用Java調(diào)用Linux系統(tǒng)命令
這篇文章主要介紹了如何使用Java調(diào)用Linux系統(tǒng)命令,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
Java實現(xiàn)將枚舉類轉(zhuǎn)為json并返回給前端
這篇文章主要為大家詳細介紹了Java實現(xiàn)將枚舉類轉(zhuǎn)為json并返回給前端的相關知識,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-12-12
java并發(fā)之ArrayBlockingQueue詳細介紹
這篇文章主要介紹了java并發(fā)之ArrayBlockingQueue詳細介紹的相關資料,需要的朋友可以參考下2017-05-05
Springboot2.x 使用 Log4j2 異步打印日志的實現(xiàn)
這篇文章主要介紹了Springboot2.x 使用 Log4j2 異步打印日志的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12
Spring Boot2開發(fā)之Spring Boot整合Shiro兩種詳細方法
這篇文章主要介紹了Spring Boot2開發(fā)之Spring Boot整合Shiro詳細方法,需要的朋友可以參考下2020-03-03
Java數(shù)據(jù)結(jié)構(gòu)之有效隊列定義與用法示例

