• SpringBoot整合注解式mybatis


    1. 创建Spring Boot项目: 创建一个Spring Boot项目,可以使用Spring Initializer或手动创建

    2. 添加依赖:pom.xml文件中,添加Spring Boot、MyBatis和数据库驱动程序的依赖,就像之前所示。

    1. org.springframework.boot
    2. spring-boot-starter-web
    3. org.mybatis.spring.boot
    4. mybatis-spring-boot-starter
    5. 2.3.1
    6. org.springframework.boot
    7. spring-boot-starter-test
    8. test
    9. org.mybatis.spring.boot
    10. mybatis-spring-boot-starter-test
    11. 2.3.1
    12. test
    13. mysql
    14. mysql-connector-java

    3. 配置数据源:application.propertiesapplication.yml文件中配置数据库连接信息。例如:

    1. spring:
    2. datasource:
    3. driver-class-name: com.mysql.cj.jdbc.Driver
    4. url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useSSL=true
    5. username: root
    6. password: 123456

    4. 创建实体类: 创建实体类和数据库表之间的映射,可以使用@Entity注解,也可以使用@Table@Id等MyBatis或JPA的注解。

    1. package com.example.demo.entity;
    2. import lombok.Data;
    3. @Data
    4. public class Sample {
    5. private Long id;
    6. private String name;
    7. private String sex;
    8. private int age;
    9. }

    5. 创建Mapper接口: 创建一个MyBatis的Mapper接口,并使用@Mapper注解进行标记。

    1. package com.example.demo.mapper;
    2. import com.example.demo.entity.Sample;
    3. import org.apache.ibatis.annotations.Mapper;
    4. import java.util.List;
    5. @Mapper
    6. public interface SampleMapper {
    7. List findAll();
    8. }

    6.创建Service层: 创建Service层,处理业务逻辑,并将Mapper接口注入Service中。

    1. public interface SampleService {
    2. public List findAll();
    3. }
    1. import java.util.List;
    2. @Service
    3. public class SampleServiceImpl implements SampleService{
    4. @Autowired
    5. SampleMapper sampleMapper;
    6. @Override
    7. public List findAll() {
    8. return sampleMapper.findAll();
    9. }
    10. }

     7. 创建Controller: 创建一个Controller层,处理HTTP请求,调用Service层的方法。

    这里注意要使用RestController注解不能用Controller不然前端调用会报404

    1. @RequestMapping("sample")
    2. @RestController
    3. public class SampleController {
    4. @Resource
    5. SampleService sampleService;
    6. @GetMapping("find-all")
    7. public List list(){
    8. List all = sampleService.findAll();
    9. return all;
    10. }
    11. }

    8. 配置Mapper扫描路径: 使用@MapperScan注解来指定MyBatis的Mapper接口扫描路径,通常在Spring Boot应用的启动类上使用。

    1. @SpringBootApplication
    2. @MapperScan("com.example.demo.mapper")
    3. public class DemoApplication {
    4. public static void main(String[] args) {
    5. SpringApplication.run(DemoApplication.class, args);
    6. }
    7. }

  • 相关阅读:
    springboot+vue学习用品商店商城系统java毕业设计ucozu
    c语言进阶篇:自定义类型--位段、枚举and联合体
    Gin + Element + 云IDE 挑战一小时打造春联生成平台
    QT启动 一个进程-一个exe文件方法
    关于我的博客~ (2022.8.25 -> 在csdn三岁啦)
    C++之前置声明
    String的理解
    搭建WAMP网站教程(Windows+Apache+MySQL+PHP)
    openlayers+vue的bug
    基于 LSTM 的分布式能源发电预测(Matlab代码实现)
  • 原文地址:https://blog.csdn.net/Candy___i/article/details/133998348