springboot 3 下连接 mysql 数据库以及整合 mybatis-plus

27 篇文章 0 订阅

测试示例

在 Springboot 3.x版本下整合 mysql 以及mybatis-plus,并进行简单测试,解决实现过程中所遇到的常见 Bug。

引入依赖

<!-- 数据库驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus 3.5.3 才支持 spring boot 3-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3</version>
</dependency>

配置 application.yml

# mysql 配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/community?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
    username: root
    password: yumuing
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      maximum-pool-size: 15
      minimum-idle: 5
      idle-timeout: 30000
# mybatis-plus 配置

mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    use-generated-keys: true
  mapper-locations: classpath*:mapper/**/*Mapper.xml
  type-aliases-package: top.yumuing.community.entity

创建 MySQL 数据库

创建 community 数据库,运行以下 SQL 代码完成数据表创建:

INSERT INTO user (id, name, email) VALUES
(1, 'Jone', 'test1@baomidou.com'),
(2, 'Jack','test2@baomidou.com'),
(3, 'Tom','test3@baomidou.com'),
(4, 'Sandy', 'test4@baomidou.com'),
(5, 'Billie','test5@baomidou.com');

Query OK, 5 rows affected (0.01 sec)
Records: 5  Duplicates: 0  Warnings: 0
mysql> DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int DEFAULT NULL,
  `name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `age` int DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

测试 MySQL 连接

@Resource
DataSource dataSource;

@Test
void contextLoadsOne() throws Exception{
    System.out.println("获取的数据库连接为:"+dataSource.getConnection());
}

控制台输出以下内容即为 MySQL 连接配置成功:

获取的数据库连接为:HikariProxyConnection@54056059 wrapping com.mysql.cj.jdbc.ConnectionImpl@5611bba

测试整合 Mybatis-plus 简单配置

@Resource
private UserMapper userMapper;

@Test
void contextLoadsTwo() {
    List<User> list = userMapper.selectList(null);
    list.forEach(item-> System.out.println(item));
}

控制台输出以下内容即为配置 Mybatis-plus 成功

User(id=1, name=张三, age=20)
User(id=2, name=李四, age=22)
User(id=3, name=王五, age=30)

当然,我们也可以使用 MybatisX 插件对 mapper.class、mapper.xml、service.class、serviceImpl.class 进行生成,步骤如下:

并且,我们也能够使用 MybatisX 插件实现 xml 文件中,mapper 对应的 SQL 代码,在 mapper.class 中写出想要在 xml 中生成代码的方法名,一定要以 select、insert、update等等进行开头,之后就会有对应提示,选中即可,完成后,往前几格子,方法名变红,选择报错点右键选中以下内容即可生成相关代码:

xml 文件中 selectAllByIdOrderByAge 生成代码如下:

<sql id="Base_Column_List">
    id,name,age
</sql>
<select id="selectAllByIdOrderByAge" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from user
    where
    id = #{id,jdbcType=NUMERIC}
    order by age
</select>

测试代码如下:

@Test
void cotextLoadsFour(){
    List<User> users = userMapper.selectAllByIdOrderByAge(3);
    users.forEach(item-> System.out.println(item));
}

Bug 总结

Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required

springboot 3版本整合 mybatis 3.0.5版本控制台报错 Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required,NestedIOException 这个类在 Spring 6 版本中直接删除了。对的,直接删除了。而 MyBatis 老版本还没有同步更新,所以直接就报红了。而整合 mybatis 的 mybatis-plus 自然也会报红。

2022 年 11 月26 日凌晨,mybatis-spring-boot 正式发布 3.0.0 版本,完全支持 Spring Boot 3 了。mybatis-plus 也在 2022.12.28 的 3.5.3 支持了 Spring Boot 3 。最好解决办法就是升级版本。

Could not autowire. No beans of ‘DataSource’ type found

  1. 检查项目结构,主启动类位置是否正确

  1. 把自动装配@Autowired换成@Resource

Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl

该报错是配置文件路径错误,重点检查url路径,3306后的 test 为数据库名,注意修改成数据库已有数据库名

mysql8.x版本URL为 jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8

Cannot resolve method 'assertEquals' in 'Assert'

在测试方法中,使用该方法报错,没引入 import org.junit.Assert; 的Assert 包,解决方法如下:

  1. 引入 junit 依赖

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
  1. 导入正确包 import org.junit.Assert; 的Assert

Injection of resource dependencies failed

测试方法控制台输出:Injection of resource dependencies failed

确定报错对象为 userMapper,发现没有指定 MapperScan,解决如下:

在启动类加入:@MapperScan("top.yumuing.community.mapper") 即可

Could not autowire. No beans of 'DataSource' type found.

编译报错:Could not autowire. No beans of 'DataSource' type found. 代码如下:

@Autowired
DataSource dataSource;

修改 @Autowired 为 @Resource 即可解决

Could not autowire. No beans of 'UserMapper' type found.

@Autowired
private UserMapper userMapper;

修改 @Autowired 为 @Resource 即可解决

  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
你好!要在Spring Boot整合MyBatis-Plus,你可以按照以下步骤进行操作: 步骤1:添加依赖 在你的Spring Boot项目的pom.xml文件中,添加MyBatis-Plus的依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本号</version> </dependency> ``` 请确保将`最新版本号`替换为MyBatis-Plus最新的版本号。 步骤2:配置数据源 在application.properties(或application.yml)文件中,配置数据库连接信息,例如: ```yaml spring.datasource.url=jdbc:mysql://localhost:3306/db_example spring.datasource.username=db_username spring.datasource.password=db_password spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 请将`db_example`、`db_username`和`db_password`分别替换为你的数据库名称、用户名和密码。 步骤3:创建实体类和Mapper接口 创建对应的实体类,并使用`@TableName`注解指定数据库表名。然后创建Mapper接口,继承自`BaseMapper`。 ```java import com.baomidou.mybatisplus.annotation.TableName; @TableName("user") public class User { private Long id; private String username; private String email; // getters and setters } ``` ```java import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface UserMapper extends BaseMapper<User> { } ``` 步骤4:编写Service和Controller层代码 在Service层中,可以通过注入Mapper对象来使用MyBatis-Plus提供的便捷方法。例如: ```java import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Override public User getUserById(Long id) { return userMapper.selectById(id); } // 其他业务逻辑方法 } ``` 在Controller层中,可以直接调用Service层的方法来处理请求。例如: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class UserController { @Resource private UserService userService; @GetMapping("/users/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } // 其他请求处理方法 } ``` 这样,你就完成了Spring BootMyBatis-Plus整合。你可以根据自己的需求,使用MyBatis-Plus提供的便捷方法来进行数据库操作。 希望对你有所帮助!如果还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一枚务实的码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值