springboot + mybatis-plus 实现增删改查

一. 添加依赖

        
        
            mysql
            mysql-connector-java
            runtime
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.5.1
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.5.2
        
        
        
            org.freemarker
            freemarker
            2.3.29
        
        
        
            javax.validation
            validation-api
            2.0.1.Final
        
        
        
            org.projectlombok
            lombok
            true
        

二. 配置application.properties文件

server.port=9800

#dbname为具体连接的数据库名
spring.datasource.url=jdbc:mysql://localhost:3306/dbname?&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#上传文件大小限制
spring.servlet.multipart.max-file-size=10000MB
spring.servlet.multipart.max-request-size=10000MB

#xml文件存放位置为resources目录下新建mapper文件夹
mybatis-plus.global-config.db-config.logic-delete-field=isDeleted
mybatis-plus.mapper-locations=classpath:mapper/*.xml
mybatis-plus.type-aliases-package=com.example.collection.dao

三. 代码实现

        1. 新建mybatis-plus配置文件MybatisPlusConfig

@Configuration
@MapperScan("com.example.collection.dao")
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

}

其中mapper文件存放在dao文件夹下

        2. 新建统一返回类CommonResult

public class CommonResult {

    private T data;
    private String msg;
    private Integer code;

    public CommonResult() {

    }

    public CommonResult(T data) {
        this.data = data;
        this.msg = "success";
        this.code = 200;
    }

    public CommonResult(T data, String msg, Integer code) {
        this.data = data;
        this.msg = msg;
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

       3. 新建User类及PageParam分页类

@TableName(value = "user", autoResultMap = true)
public class User {

    private Long id;

    private String account;

    private String username;

    private String password;

    //get&set...
}
public class PageParam {

    @ApiModelProperty("当前页, 默认1")
    private long current = 1;
    @ApiModelProperty("每页显示条数,默认10")
    private long size = 10;
    @ApiModelProperty("正序排列字段,多个以逗号隔开")
    private String ascs;
    @ApiModelProperty("反序排列字段,多个以逗号隔开")
    private String descs;

    /**
     * 将分页参数转换成Page
     *
     * @param  实体类型
     * @return Page
     */
    public  Page toPage() {
        Page page = new Page<>();
        page.setCurrent(this.getCurrent());
        page.setSize(this.getSize());
        if (StrUtil.isNotBlank(this.getAscs())) {
            page.addOrder(OrderItem.ascs(this.getAscs().split(",")));
        }
        if (StrUtil.isNotBlank(this.getDescs())) {
            page.addOrder(OrderItem.descs(this.getDescs().split(",")));
        }
        return page;
    }

    //set&get...

}

        4. Dao层及其实现

                1.在dao目录下新建文件

public interface UserMapper extends BaseMapper {

}

                2.在resources目录下新建mapper文件夹,其中存放对应的xml文件。

                      其中命名空间namespace一定要准确对应mapper文件





           5. Service层及其实现

public interface UserService extends IService {

    void removeUser(List ids);

    IPage pageUser(PageParam page, String account);

}
@Service
public class UserImpl extends ServiceImpl implements UserService {

    @Override
    public void removeUser(List ids) {
        for (Long id: ids) {
            lambdaUpdate()
                    .eq(User::getId, id)
                    .remove();
        }
    }

    @Override
    public IPage pageUser(PageParam page, String account) {
        return this.lambdaQuery()
                .eq(StrUtil.isNotEmpty(account), User::getAccount, account)
                .page(page.toPage());
    }

}

            6. Controller层及其实现

@RestController
@RequestMapping("/user")
@CrossOrigin(value = "*",  maxAge = 3600)
public class UserController {

    @Resource
    private UserService server;

    //用户注册
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public CommonResult saveUser(@RequestBody User user) {
        //在数据库中将account字段设置为unique,不允许字段值重复
        try {
            server.save(user);
            return new CommonResult<>("创建成功");
        } catch (Exception e) {
            return new CommonResult<>("创建失败,账号已存在", "Bad Request",400);
        }
    }


    //查询用户列表(可以传入account精准查询或不传account批量查询)
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public CommonResult queryUserList(
            PageParam page,
            @RequestParam(required = false, value = "account") String account) {
        return new CommonResult(server.getUserList(page, account));
    }

    //删除用户
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public CommonResult removeUser(@RequestBody List ids) {
        server.removeUser(ids);
        return new CommonResult("成功删除", "Delete Failed", 200);
    }


}

你可能感兴趣的:(mybatis,spring,boot,java)