栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot项目 结合 MyBatis使用范例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot项目 结合 MyBatis使用范例

SpringBoot项目 结合 MyBatis使用范例 1.案例的介绍 1.1 SpringBoot
  • 因为遵循着约定优于配置的规范,所以在快速开发的时候非常方便
1.2 MyBatis
  • MyBatis 是 SSM 项目中的 M,主要负责人项目与数据库之间的相关操作,在项目中作用体现在持久层(有的也称为数据层)
2.IDEA 构建项目 2.1 IDEA 初始化项目
  • 此处我使用的是 ALiBaBa 的国内源:https://start.aliyun.com/
  • 指定项目的基本信息
  • 添加相关的依赖
  • 连接数据库,生成对应的实体对象
2.2 进行项目代码的编写
  • 生成数据表对应的实体类
package com.lagou.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class Comment implements Serializable {
    private static final long serialVersionUID = -20796280730949307L;
    
    private Integer id;
    
    private String content;
    
    private String author;
    
    private Integer aId;
}
  • 编写对应的mapper接口
package com.lagou.dao;

import com.lagou.entity.Comment;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public interface CommentDao {
    // 根据 id 查询对应的记录
    public Comment findById(Integer id);
}
  • 编写对应的 mapper 映射文件




    
        
        
        
        
    

    
        select * from t_comment where id = #{id}
    


  • 编写 配置文件
# 端口
server:
  port: 8888
# 应用名称
spring:
  application:
    name: springboot-mybatis
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.159.133:3306/springbootdata?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: liuyunfei
    password: Lyf123456!

# MyBatis 配置
mybatis:
  configuration:
    # 驼峰命名法
    map-underscore-to-camel-case: true
  # 指定映射文件
  mapper-locations: classpath:mapper
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentDao commentDao;

    @RequestMapping("/{id}")
    public Comment getCommentById(@PathVariable("id") Integer id){
        Comment comment = commentDao.findById(id);
        return comment;
    }
}
  • 首先启动项目

  • 浏览器进行接口的访问:http://127.0.0.1:8888/comment/1

3.总结

以上就是 SpringBoot 结合 MyBatis 使用的案例,虽然简单,但是基本功能都已经实现了,希望可以帮助到大家

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/981245.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号