SpringBoot integration MybatisPlus 3.0

 
CRUD refers to an increase (Create) to do the calculation processing of read queries (Retrieve), update (Update) and delete (Delete) a few words of the first letter abbreviation. The basic operating functions are primarily used in the description of a software system or permanent layer DataBase

Requirements:
there is a message table, and the corresponding entity class Message has been achieved message table CRUD operations what we need to do?
Based Mybatis:
need to write MessageMapper interface and write sql statement CRUD methods corresponding manually MessageMapper.xml mapping file.
Based on MP:
Just create MessageMapper interface and inheritance BaseMapper interface.
We already have a Message, message, and also inherited BaseMapper and MessageDao, the next on the use of crud method.

Preface:

mybatis the persistence framework is still relatively fire, general project ssm are based. Although mybatis in xml can operate the database through SQL statements directly, very flexible. But it is its operation should be carried out by SQL statements, you have to write a lot of xml file, it is troublesome. mybatis-plus a good solution to this problem.

A, mybatis-plus Description:

Mybatis-Plus (abbreviated MP) is a Mybatis enhancement tools, enhanced not only changed on the basis of Mybatis to simplify development, increase efficiency and health. This is the official definition given, more of the description and characteristics about mybatis-plus, reference may be mybatis-plus official website . So how did it enhance it? In fact, it has a good package of some crud methods, we do not need to write xml, and call these methods directly on the line, similar to JPA.

Two, spring integration mybatis-plus:

As the official said, mybatis-plus enhanced not only changed on the basis of mybatis, its integration with the spring is also very simple. Simply mybatis depends replaced rely mybatis-plus, and then replaced sqlSessionFactory to mybatis-plus of. Next, look at the specific operation:
. 1, the pom.xml:
Core dependence follows:

<-! Druid database connection pool launcher ->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.9</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
    <version>5.1.46</version>
</dependency>
<-! Mybatis-plus starters ->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.0.1</version>
</dependency>
Note: These are dependent on the core, the project also uses the mysql driver, c3p0, log (slf4j-api, slf4j-log4j2 ), lombok. Integrated mybatis-plus should mybatis, mybatis-spring removed, to avoid conflict; lombok is a tool to add this dependence, development tools, and then install the plug-in Lombok, you can use it, the most common usage is to use it in the entity class the @Data notes, so do not write like entity set, get, toString methods such as the. For more usage of Lombok, your own Baidu.
2, application.properties configuration:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.url=jdbc:mysql://localhost:3306/mp_demo?useUnicode=true&characterEncoding=utf-8&useSSL=false

3, the preparation of entity classes:

/**
 * @create 2019.08.14
 **/
@AllArgsConstructor
@NoArgsConstructor
@Accessors
@Data
@TableName(value = "message")
public class Message implements Serializable {
  //value与数据库主键列名一致,若实体类属性名与表主键列名一致可省略value
    @TableId(value = "id",type = IdType.AUTO)//指定自增策略 
    private Integer id;
    private Integer mid;
    private String content;
    @TableField(value = "column_200")
    private String column1;
    @TableField(value = "column_500")
    private String column2;
    @TableField(value = "column_5000")
    private String column3;
}

解说:(1)@TableName是mybatis plus对表的注解,每个实体必须要加,不然会导致表不存在异常。

        (2)@TableId对主键的注解 @TableId中有一个属性叫type是枚举类型,该属性主要作用是主键以什么形式存在,例如IdType.AUTO自增或UUID。

        (3)@TableField像及了mybatis中的resultMap,在mybatis中为什么要使用resultMap,因为当实体中的属性名与数据库中的表不一致时需要手动映射,resultMap的作用在于手动映射,既然说了resultMap就不能不说resultType,resultType当实体属性与表字段一致时自动映射。 在mybatis plus使用@TableField的场景与mybatis中使用resultMap的是一致的。@TableField中还有一个属性不能不提,就是exist,这个属性属于boolean类型,默认为true,意思是是否在数据表中存在,true存在,false不存在,这个的应用场景是当某个实体中需要包含其他实体时,可使用该属性,否则自动生成的查会报错,使用自动生成的查有关方法,默认是查所有数据表所有字段,当然可使用setSqlSelect()方法指定需要查的字段,可以在一定程度上避免该错误的出现,不然导致的错误最有可能就是找不到该字段异常(column not exist),使用exist属性可直接避免,当然也可以在该属性中加入static或transient修饰,与exist的作用本质上是一样的。

4.、编写mapper接口继承BaseMapper接口的数据操作方法:

/**
 * @create 2019.08.14
 **/
@Mapper
public interface MessageMapper extends BaseMapper<Message> {}

解说:BaseMapper<T>中包含的就是一系列增删改查,maven项目中可Ctrl+鼠标点击进去查看源码,源码所有注释都有,非常浅显易懂,如果你需要加入自定义sql直接写就行,跟mybatis一样,在该类中新增方法,只需在对应的xml中配置即可

5、编写Service

/**
 * @create 2019.08.14
 **/
public interface MessageService {
    List<Message> getAllMessage();
    List<Message> getMessageByMid(Integer mid);
    Integer fetchOne(Integer id,Integer mid);
    Integer updateMessageByModuleIdAndMessageId(Message message);
    Integer addMessage(Message message);
    Integer deleteMessage(Integer mid,Integer id);
}

Service实现类:

/**
 * @create 2019.08.14
 **/
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public List<Message> getAllMessage() {
        return messageMapper.selectList(new QueryWrapper<Message>());
    }

    @Override
    public List<Message> getMessageByMid(Integer mid) {
        return messageMapper.selectList(new QueryWrapper<Message>().eq("mid",mid));
    }

    @Override
    public Integer fetchOne(Integer id,Integer mid){
        return messageMapper.selectCount(new QueryWrapper<Message>().eq("id",id).eq("mid",mid));
    }

    @Override
    public Integer updateMessageByModuleIdAndMessageId(Message message){
        System.out.println(message);
        logger.debug(message.toString());
        return messageMapper.updateById(message);
    }
    @Override
    public Integer addMessage(Message message){
        System.out.println(message);
        logger.debug(message.toString());
        return messageMapper.insert(message);
    }
    @Override
    public Integer deleteMessage(Integer mid,Integer id){
        logger.debug(mid+"-"+id);
        return messageMapper.delete(new QueryWrapper<Message>().eq("id",id).eq("mid",mid));
    }
}

解说:@Service注解的作用也是同mybatis之前那样也是一样,这个注解的作用扫描Service层,自动注解spring容器

6、编写Controller

/**
 * @create 2019.08.14
 **/
@RestController
public class MainController {
    @Autowired
    private MessageService messageService;

    @GetMapping("/messages")
    public ModelMap getMessages(){
        ModelMap map = new ModelMap();
        return map.addAttribute("messages",messageService.getAllMessage());
    }

    @GetMapping("module1")
    public Object getMessageType1(){
        return messageService.getMessageByMid(1);
    }
    
    @GetMapping("module2")
    public Object getMessageType2(){
        return messageService.getMessageByMid(2);
    }
    
    @PostMapping("/message")
    public ModelMap addMessage(@RequestBody Message message){
        ModelMap map = new ModelMap();
        Integer result = messageService.addMessage(message);
        if (result==1){
            map.addAttribute("result",true);
            map.addAttribute("tip","添加成功!");
        }else{
            map.addAttribute("result",false);
            map.addAttribute("tip","添加失败!");
        }
        return map;
    }
    
    @DeleteMapping("/{mid}/{id}")
    public ModelMap deleteMessage(@PathVariable Integer mid,@PathVariable Integer id){
        System.out.println(mid);
        System.out.println(id);
        ModelMap map = new ModelMap();
        Integer result = messageService.deleteMessage(mid,id);
        if (result==1){
            map.addAttribute("result",true).addAttribute("tip","删除成功!");
        }else{
            map.addAttribute("result",false).addAttribute("tip","删除失败!");
        }
        return map;
    }
    
    @PatchMapping("/message")
    public ModelMap updateMessage(@RequestBody Message message){
        Integer one = messageService.fetchOne(message.getId(), message.getMid());
        ModelMap map = new ModelMap();
        if (one==1){
            Integer result = messageService.updateMessageByModuleIdAndMessageId(message);
            if (result==1){
                map.addAttribute("result",true).addAttribute("tip","更新成功!");
            }else{
                map.addAttribute("result",false).addAttribute("tip","更新失败!");
            }
            System.out.println(message);
        }else{
            map.addAttribute("tip","查询异常!");
        }
        return map;
    }
}

7、显示结果:

 

https://yq.aliyun.com/articles/713779?spm=a2c4e.11163080.searchblog.9.5b4f2ec1UxSaKD
 

Guess you like

Origin www.cnblogs.com/ajing2018/p/11352885.html