Mybatis-plus基本使用(demo)

以前没用过mybatis-plus,最近用到了就稍微记录一下。

1.创建项目
在这里插入图片描述

2.pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.8</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.scy</groupId>
	<artifactId>test</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>test</name>
	<description>test</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>
		
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.2.6</version>
		</dependency>
		
		<!--mybatisplus-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

3.application.yml文件

server:
  port: 9001

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
    type: com.alibaba.druid.pool.DruidDataSource

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

4.userMapper

package com.scy.test.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.scy.test.entiy.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper extends BaseMapper<User> {
}

5.userService

package com.scy.test.service;

import com.scy.test.entiy.User;

import java.util.List;

public interface UserService {
    List<User> getUserList();

    int insertUser(User user);

    int delUser(int id);

    int updUser(User user);

    User getUserByid(int id);

}

6.userServiceImpl

package com.scy.test.service.impl;

import com.scy.test.entiy.User;
import com.scy.test.mapper.UserMapper;
import com.scy.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    /**
     * 获取所有的结果
     * @return
     */
    @Override
    public List<User> getUserList() {
        return userMapper.selectList(null);
    }

    /**
     * 新增
     * @param user
     * @return
     */
    @Override
    public int insertUser(User user) {
        return userMapper.insert(user);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public int delUser(int id) {
        return userMapper.deleteById(id);
    }

    /**
     * 修改
     * @param user
     * @return
     */
    @Override
    public int updUser(User user) {
        return userMapper.updateById(user);
    }

    //按id查询
    @Override
    public User getUserByid(int id) {
        return userMapper.selectById(id);
    }

}

7.userController

package com.scy.test.controller;

import com.scy.test.entiy.User;
import com.scy.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
        @Autowired
        UserService userService;

        /**
         * 查询所有信息
         */
        @RequestMapping("getUserList")
        public List<User> getUserList(){
            return userService.getUserList();
        }

        /**
         *按id查询
         */
        @RequestMapping("getUserByid")
        public User getUserByid(@RequestParam int id){
            return userService.getUserByid(id);
        }
        /**
         *新增
         */
        @RequestMapping("insertUser")
        public Map<String,String> insertUser(@RequestParam int id, @RequestParam String name, @RequestParam int age, @RequestParam String email){
            User user = new User();
            user.setId(id);
            user.setName(name);
            user.setAge(age);
            user.setEmail(email);
            int i = userService.insertUser(user);
            String msg = i>0 ? "success" : "error" ;
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("msg",msg);
            return resultMap;
        }
        /**
         *删除用户
         */
        @RequestMapping("delUser")
        public Map<String,String> delUser(@RequestParam int id){
            int i = userService.delUser(id);
            String msg = i>0 ? "success" : "error" ;
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("msg",msg);
            return resultMap;
        }
        /**
         *修改用户
         */
        @RequestMapping("updUser")
        public Map<String,String> updUser(@RequestParam int id, @RequestParam String name, @RequestParam int age, @RequestParam String email){
            User user = new User();
            user.setId(id);
            user.setName(name);
            user.setAge(age);
            user.setEmail(email);
            int i = userService.updUser(user);
            String msg = i>0 ? "success" : "error" ;
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("msg",msg);
            return resultMap;
        }
    }

8.启动类

package com.scy.test;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.scy.test.mapper")
public class TestApplication {

	public static void main(String[] args) {
		SpringApplication.run(TestApplication.class, args);
	}

}

记得去创建对应的数据库和对应实体类的表,然后去调用对应的路径就可以了。
(http://localhost:9001/xxx)

最后说一下:比较简单的增删改查,Mybatis-plus都帮我们写好了,所以mapper和映射不用写就可以了,如果后面有比较难的业务,sql还是要自己写,但是对于程序员来说这已经帮我们减少很多工作量了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个简单的MyBatis-Plus使用示例: 1. 首先,确保你已经在项目中引入了MyBatis-Plus的依赖。 2. 创建一个实体类,例如User: ```java @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; private String email; } ``` 3. 创建一个Mapper接口,继承BaseMapper,并定义一些自定义的查询方法: ```java public interface UserMapper extends BaseMapper<User> { List<User> selectByName(String name); } ``` 4. 在配置文件中配置Mapper扫描路径: ```yaml mybatis-plus: mapper-locations: classpath:mapper/*.xml ``` 5. 编写SQL映射文件,例如UserMapper.xml,定义一些自定义的SQL语句: ```xml <mapper namespace="com.example.mapper.UserMapper"> <select id="selectByName" resultType="com.example.entity.User"> SELECT * FROM user WHERE name = #{name} </select> </mapper> ``` 6. 在Service层中使用MyBatis-Plus提供的方法进行CRUD操作: ```java @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> getUserByName(String name) { return userMapper.selectByName(name); } } ``` 7. 在Controller层中调用Service层的方法进行接口暴露: ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{name}") public List<User> getUserByName(@PathVariable String name) { return userService.getUserByName(name); } } ``` 这样,你就可以通过访问`/users/{name}`接口来获取指定名称的用户信息了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值