提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
数据访问
一、准备数据库表
`CREATE TABLE `t_user`
(
`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
`login_name` VARCHAR(200) NULL DEFAULT NULL COMMENT '用户名称' COLLATE 'utf8_general_ci',
`nick_name` VARCHAR(200) NULL DEFAULT NULL COMMENT '用户昵称' COLLATE 'utf8_general_ci',
`passwd` VARCHAR(200) NULL DEFAULT NULL COMMENT '用户密码' COLLATE 'utf8_general_ci',
PRIMARY KEY (`id`)
);
INSERT INTO t_user(login_name, nick_name, passwd) VALUES ('zhangsan','张三','123456');`t_user``t_user`
二、项目创建
2.1、使用spring initializer 创建
选择lomback,springweb,mybatis,mysql
编写bean
package com.cky.shujufangwen.bean;
import lombok.Data;
/**
* @ClassName User
* @Description TODO
* @Author lukcy
* @Date 2024/6/10 9:15
* @Version 1.0
*/
@Data
public class User {
private Long id;
private String loginName;
private String nickName;
private String passwd;
}
2.2、添加数据库配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
2.3 mapper
生成mqpper,并且用mybatis X插件来创建对应的.XML文件
#指定mapper映射文件位置
mybatis.mapper-locations=classpath:/mapper/*.xml
#参数项调整
mybatis.configuration.map-underscore-to-camel-case=true
开启驼峰式映射
2.4 编写controller
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping(value = "user/{id}")
public User getUser(@PathVariable("id") long id){
User user=userMapper.getUserById(id);
return user;
}
}
2.5 总结
SSM整合总结:
- 导入 mybatis-spring-boot-starter
- 配置数据源信息
- 配置mybatis的mapper接口扫描与xml映射文件扫描
- 编写bean,mapper,生成xml,编写sql 进行crud。事务等操作依然和Spring中用法一样
- 效果:
a. 所有sql写在xml中
b. 所有mybatis配置写在application.properties下面
三、其他数据源
springboot3 整合 Druid 数据源
首先,在你的Spring Boot项目中添加Druid的依赖。在 pom.xml文件中添加以下依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
接下来,在 application.properties(或 application.yml)文件中配置Druid的数据源信息,例如:
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Druid specific configuration
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;
druid.stat.slowSqlMillis=5000