Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java mybatisplus

作者:潮起潮落   发布日期:2025-06-21   浏览:43

// 引入 MyBatis-Plus 相关依赖
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
</dependency>

// 实体类 User
package com.example.demo.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

@TableName("user")
public class User {
    @TableId
    private Long id;
    private String name;
    private Integer age;

    // getter 和 setter 方法
}

// Mapper 接口
package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
    // 可以添加自定义查询方法
}

// Service 层
package com.example.demo.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.UserMapper;
import com.example.demo.entity.User;
import org.springframework.stereotype.Service;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {
    // 可以添加自定义业务逻辑
}

// Controller 层
package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.list();
    }

    @PostMapping
    public boolean addUser(@RequestBody User user) {
        return userService.save(user);
    }

    @PutMapping("/{id}")
    public boolean updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        return userService.updateById(user);
    }

    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Long id) {
        return userService.removeById(id);
    }
}

解释说明:

  1. 引入依赖:在 pom.xml 文件中添加 MyBatis-Plus 的依赖,确保项目可以使用 MyBatis-Plus 的功能。
  2. 实体类 User:使用 @TableName 注解指定数据库表名,并通过 @TableId 注解标识主键字段。
  3. Mapper 接口 UserMapper:继承 BaseMapper,MyBatis-Plus 提供了丰富的 CRUD 操作方法,无需编写 SQL 语句。
  4. Service 层 UserService:继承 ServiceImpl,实现对 UserMapper 的封装,提供业务逻辑处理。
  5. Controller 层 UserController:提供 RESTful API 接口,用于增删改查用户信息。

通过以上代码示例和解释,您可以快速搭建一个基于 MyBatis-Plus 的 Java 项目。

上一篇:java string分割成数组

下一篇:java 读取文本文件

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站