MyBatis-Plus?UserMpper接口示例實(shí)現(xiàn)
UserMapper 接口示例
在 MyBatis-Plus 中,UserMapper 是一個(gè)非常簡單但功能強(qiáng)大的接口。它通常長這樣:
基本結(jié)構(gòu)
package com.example.mapper; // 根據(jù)你的項(xiàng)目結(jié)構(gòu)調(diào)整包名
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.User; // 你的User實(shí)體類所在的包
import org.apache.ibatis.annotations.Mapper;
// 使用@Mapper注解讓Spring管理這個(gè)接口,并生成實(shí)現(xiàn)類
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 不需要寫任何方法,就已經(jīng)繼承了BaseMapper中的所有CRUD方法
// 但你也可以根據(jù)需要添加自定義方法
}
詳細(xì)解釋
1. 必需的組成部分
繼承 BaseMapper<T>:這是最關(guān)鍵的部分,通過繼承并指定泛型類型為你的實(shí)體類(這里是 User),你的 UserMapper 就自動(dòng)獲得了 BaseMapper 中定義的約 20 個(gè)常用 CRUD 方法。
@Mapper 注解:這個(gè)注解告訴 MyBatis 這是一個(gè)映射器接口,Spring 啟動(dòng)時(shí)會(huì)自動(dòng)為其創(chuàng)建代理實(shí)現(xiàn)類。
2. 完整的示例(包含實(shí)體類和配置)
為了讓示例更完整,這里也展示一下相關(guān)的 User 實(shí)體類和 Spring Boot 配置:
User 實(shí)體類 (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í)體類對(duì)應(yīng)的數(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 # 實(shí)體類包路徑
configuration:
map-underscore-to-camel-case: true # 自動(dòng)開啟駝峰命名轉(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表達(dá)式避免硬編碼字段名
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 提供了豐富的通用方法,但有時(shí)你可能需要添加自定義查詢:
@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 接口的核心特點(diǎn)是:
- 繼承
BaseMapper<User>,自動(dòng)獲得大量CRUD方法 - 使用
@Mapper注解標(biāo)記為MyBatis映射器 - 不需要編寫任何實(shí)現(xiàn)代碼,MyBatis-Plus會(huì)自動(dòng)生成代理實(shí)現(xiàn)
- 可以添加自定義方法滿足特定業(yè)務(wù)需求
這種設(shè)計(jì)極大地減少了傳統(tǒng)MyBatis中需要編寫的模板代碼,讓開發(fā)者能夠更專注于業(yè)務(wù)邏輯的實(shí)現(xiàn)。
到此這篇關(guān)于MyBatis-Plus UserMpper接口示例的文章就介紹到這了,更多相關(guān)MyBatis-Plus UserMpper接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java枚舉(Enum)從基礎(chǔ)到高級(jí)應(yīng)用詳解
文章詳細(xì)介紹了Java枚舉(enum)的概念、基礎(chǔ)語法、內(nèi)置方法及高級(jí)用法,強(qiáng)調(diào)了枚舉在提高代碼類型安全性、可讀性和維護(hù)性方面的優(yōu)勢(shì),文中還列舉了添加字段、方法和實(shí)現(xiàn)接口等高級(jí)用法,并提供了命名規(guī)范、不可變性、異常處理等最佳實(shí)踐建議,需要的朋友可以參考下2026-05-05
Java thrift服務(wù)器和客戶端創(chuàng)建實(shí)例代碼
Thrift是一個(gè)軟件框架,用來進(jìn)行可擴(kuò)展且跨語言的服務(wù)的開發(fā)。接下來通過本文給大家介紹Java thrift服務(wù)器和客戶端創(chuàng)建實(shí)例代碼,需要的朋友參考下吧2017-04-04
IDEA啟動(dòng)Springboot報(bào)錯(cuò):無效的目標(biāo)發(fā)行版:17 的解決辦法
這篇文章主要給大家介紹了IDEA啟動(dòng)Springboot報(bào)錯(cuò):無效的目標(biāo)發(fā)行版:17 的解決辦法,文中通過代碼示例和圖文講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-02-02
spring boot udp或者tcp接收數(shù)據(jù)的實(shí)例詳解
這篇文章主要介紹了spring boot udp或者tcp接收數(shù)據(jù),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-12-12

