其他分享
首页 > 其他分享> > Mybatis-plus开发三部曲

Mybatis-plus开发三部曲

作者:互联网

 整体如下:

一是:

二是:

创建实体类:

package com.imooc.reader.entity;

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

@TableName("test") //说明实体对应哪一张表
public class Test {
    @TableId(type = IdType.AUTO)//主键标识 类型为自增主键
    @TableField("id") //说明属性对应哪个字段
    private Integer id;

    @TableField("content") //如果字段名与属性名相同或者符合驼峰命名转换规则,则TableField可省略
    private String content;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
package com.imooc.reader.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.imooc.reader.entity.Test;

public interface TestMapper extends BaseMapper<Test> {//核心父类 。传入泛型,对应的实体是哪一个
    public void insertSample();
}

id 名字要变化:

<?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.imooc.reader.mapper.TestMapper">
<!--    id 要和方法名相同-->
    <insert id="insertSample">
        insert into test(content) values('测试内容')
    </insert>
</mapper>

CRUD测试:

package com.imooc.reader;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imooc.reader.entity.Test;
import com.imooc.reader.mapper.TestMapper;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)//初始化IOC容器
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})//指向要加载的配置文件
public class MyBatisPlusTest {
    @Resource//注入已经准备好的接口
    private TestMapper testMapper;

    @org.junit.Test
    public void testInsert(){
        Test test = new Test();
        test.setContent("MyBatis Plus测试");
        testMapper.insert(test);
    }

    @org.junit.Test
    public void testUpdate(){
        Test test = testMapper.selectById(15);
        test.setContent("MyBatis Plus测试1");
        testMapper.updateById(test);
    }

    @org.junit.Test
    public void testDelete(){
        testMapper.deleteById(9);
    }
    @org.junit.Test
    public void testSelect(){
        QueryWrapper<Test> queryWrapper = new QueryWrapper<Test>();
        queryWrapper.eq("id", 7);
        queryWrapper.gt("id", 5);
        List<Test> list = testMapper.selectList(queryWrapper);
        System.out.println(list.get(0));
    }
}

 

标签:三部曲,id,Test,test,plus,Mybatis,import,com,public
来源: https://blog.csdn.net/qq_35207086/article/details/116865383