springboot+mybatis整合

本文介绍了如何使用Spring Initializr创建项目,并进行SpringBoot与Mybatis的整合。配置包括数据库连接(本地MySQL)、Mybatis映射文件设置及日志打印。通过添加实体类和配置扫描DAO文件,实现数据访问功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

1.新建一个Spring Initializr项目

 

 

2.创建项目的文件结构以及jdk的版本 

3.勾选

4.配置文件

包含三个部分

(1)数据库配置,我用的是本机安装的数据库cy,用户名和密码是root,123456(本地安装mysql请参考:(28条消息) 安装mysql 8.0+实战教程_纵与横的博客-优快云博客

(2)mybatis的映射文件配置:根目录下mappers下的所有xml文件

(3)日志打印配置

server.port= 8081

spring.datasource.url= jdbc:mysql://127.0.0.1:3306/cy
spring.datasource.username= root
spring.datasource.password= 123456
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.max-idle= 10
spring.datasource.max-wait= 10000
spring.datasource.min-idle= 5
spring.datasource.initial-size= 5


mybatis.mapper-locations= classpath:mappers/*.xml
mybatis.type-aliases-package= com.cy.test.entity

logging.level.root=INFO
logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n 
logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n
#springframework.web日志以DEBUG级别输出
logging.level.org.springframework.web=DEBUG
logging.level.com.cy.test.dao=debug

 

5.增加package和实体类(此处略过详细过程



@RestController
public class TestController {

    @Autowired
    private TestService testService;
    @RequestMapping("/index")
    public String hello() {
        return "hello";
    }

    @RequestMapping("/getAll")
    public List<User> getAll(){
       return testService.getAll();
    }
}

 

package com.cy.test.entity;

import lombok.Data;

import java.sql.Date;
@Data
public class User {

    private int id;
    private String name;
    private String grade;
    private Date birthDate;

}
@Service
public class TestService {

    @Autowired
    private TestDao testDao;

    public List<User> getAll(){

        List<User> users = testDao.queryAll();
        return users;
    }
}
@Repository
public interface TestDao {
    List<User> queryAll() ;
}

 

TestDao.xml

<?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.cy.test.dao.TestDao" >


    <select id="queryAll"  resultType="User">
        select * from runoob_tbl;
    </select>

</mapper>

 

 

6.比较关键的一步,在启动类上配置扫描dao文件

@MapperScan("com.cy.test.dao")
@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}

 

7.启动并在页面输入localhost:8081/getAll

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值