数据访问
在用SpringBoot连接数据库时遇到了很多的问题。
SQL
1、数据源的自动配置
spring已经有自己写好的数据源-HikariDataSource
1.1、引入jdbc场景
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
引入数据库驱动(spring官方默认的是8.0的驱动)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
测试代码(我是在src的main文件夹下测试的)
HellowController.java
@RestController
public class HellowController {
@Autowired
JdbcTemplate jdbcTemplate;
// user/2/owner/zhangsan
@GetMapping("/user")
public Map<String,Object> fun01(){
Map<String,Object> map = new HashMap<>();
// Goods goods = jdbcTemplate.queryForObject("select * from goods where gid = 10053", Goods.class);
Long aLong = jdbcTemplate.queryForObject("select count(*) from goods", Long.class);
System.out.println(aLong);
return map;
}
}
2、 使用Druid数据源
2.1、自定义
- 导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.17</version>
</dependency>
- 在config包下面创建一个新的MyDataSourceConfig.java类做配置文件
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class MyDataSourceConfig {
@ConfigurationProperties("spring.datasource")
@Bean
public DataSource getDataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
}
- 在容器中加入StatViewServlet组件(设置监控页)代码依旧写在MyDataSourceConfig.java
- 提供监控信息展示的html页面
- 提供监控信息的JSON API
/**
* 设置监控页
* @return
*/
public ServletRegistrationBean statViewServlet(){
StatViewServlet statViewServlet = new StatViewServlet();
ServletRegistrationBean<StatViewServlet> statViewServletServletRegistrationBean = new ServletRegistrationBean<>(statViewServlet, "/druid/*");
return statViewServletServletRegistrationBean;
}
- 设置StatFilter
- 用于统计监控信息;如SQL监控、URI监控
- 查看监控页:http://localhost:8080/druid/
2.2、引入官方stater
- 引入官方stater
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
- 更改配置文件application.yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/market
password: 123456
driver-class-name: com.mysql.jdbc.Driver
username: root
druid:
aop-patterns: com.atguigu.admin.* #监控SpringBean
filters: stat,wall # 底层开启功能,stat(sql监控),wall(防火墙)
stat-view-servlet: # 配置监控页功能
enabled: true
login-username: admin
login-password: admin
resetEnable: false
web-stat-filter: # 监控web
enabled: true
urlPattern: /*
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
filter:
stat: # 对上面filters里面的stat的详细配置
slow-sql-millis: 1000
logSlowSql: true
enabled: true
wall:
enabled: true
config:
drop-table-allow: false
- 查看监控页:http://localhost:8080/druid/
3、 整合Mybatis(认真仔细)
哇!整合的时候真的遇到好多问题,很多细节的问题一定要很认真才行(主要是多理解执行过程和内部原理,还要学着看报错信息,这样才能知道哪里出了问题)
https://mybatis.org/mybatis-3/zh/configuration.html(mybatis中文网)
3.1、整合过程
- 引入相关场景(依赖)
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
- 在resource(静态资源文件加下创建mybatis文件夹,mybatis里面创建mybatis核心配置文件mybatis-config.xml和mapper文件夹,mapper文件夹里面用来放XXXmapper.xml)
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- <environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>-->
<!-- <mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>-->
</configuration>
- 配置application.yaml(注意格式千万别写错)
mybatis:
config-location: classpath:mybatis/mybatis-config.xml #全局配置文件位置
mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件位置
- 准备好要查询的表
- bean包下创建对应的类User.java
谨记:添加注解@Component
import org.springframework.stereotype.Component;
@Component
public class User {
private int uid;
private String uname;
private String sex;
private String upass;
public User(){
}
public User(int uid, String uname, String sex, String upass) {
this.uid = uid;
this.uname = uname;
this.sex = sex;
this.upass = upass;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getUpass() {
return upass;
}
public void setUpass(String upass) {
this.upass = upass;
}
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", uname='" + uname + '\'' +
", sex='" + sex + '\'' +
", upass='" + upass + '\'' +
'}';
}
}
- mapper包里面创建接口UserMapper.java(并写入一个方法)
谨记:添加注解@Mapper
package com.miao.mapper;
import com.miao.bean.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
public User getById(Integer id);
}
- resource静态资源包下的mybatis包下的mapper包下创建UserMapper.xml
注意:mapper的namespace千万别写错
这个里面可能犯错的地方很多一定要多注意
<?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.miao.mapper.UserMapper">
<!-- public User getById(Integer id);-->
<select id="getById" resultType="com.miao.bean.User">
select * from users where uid = #{id}
</select>
</mapper>
- service包下创建UserService.java(也可以分成接口和实现类我就方便着写了)
@Service
public class UserService {
@Autowired
UserMapper usermapper;
public User getById(Integer id){
User user = usermapper.getById(id);
return user;
}
}
- controller包下创建Usercontroller.java
@RestController
public class Usercontroller{
@Autowired
UserService userService;
@GetMapping("/user")
public Map<String,Object> fun01(@RequestParam("id") Integer id){
Map<String,Object> map = new HashMap<>();
User user = userService.getById(id);
map.put("user",user);
return map;
}
}
- 启动项目,访问http://localhost:8080/user?id=101
成功
总算成功了,中间出了好多问题
3.2、注意点
(操作的表不同类名也各不相同,我以我的为准说一下注意点)
- application配置文件(spring核心配置文件)里面mybatis配置文件的位置是否正确(这个地方idea是无法智能识别的,拼错了也不会报红要注意)
- bean包下的User.java、Service包下的UserService.java、controller·包下的Usercontroller.java是否加入容器否则会找不到组件
- bean包下的User.java里面的变量是否与数据库相照应
- bean包下的User.java是否有set、get等各种方法
- mapper包下的User.java接口是否添加注解@Mapper
- UserMapper.xml里面的namespace是否正确(指向UserMapper.java)
- UserMapper.xml里面的sql语句是否正确
4、整合Mybatis-Plus(好可爱的小鸟)
mybatis-plus真的是强大诶,整合起来并不是非常难,所有人都在为更加方便简洁而奋斗
- idea安装mybatis-plus插件
我用的是离线安装(因为我在线安装搜不到插件),教程如下
https://blog.csdn.net/qq_45566354/article/details/113250595 - 项目架构如下(service要分成接口和实现类)
- User.java可以加上注解@TableName(“XXX”)里面写上对应的表名(部分代码)
@Component
@TableName("users")
public class User {
private int uid;
private String uname;
private String sex;
private String upass;
- UserMapper.java继承一个BaseMapper<>,<>里面是对应的javaBean类
@Mapper
public interface UserMapper extends BaseMapper<User> {
@Select("select * from users where uid = #{id}")
public User getById(Integer id);
}
- Service接口继承IService<>,<>里面同样为对应的javaBean类
public interface UserService extends IService<User> {
}
- Service实现类继承extends ServiceImpl<UserMapper,User>,里面是对应的Mapper接口和javaBean类
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{
}
映射文件写法和以前一样不做详细介绍
到此就可以使用插件已经提供好的方法了,下面是示例
@RestController
public class HellowController {
@Autowired
UserService userService;
@GetMapping("/user")
public Map<String,Object> fun01(){
Map<String,Object> map = new HashMap<>();
List<User> list = userService.list();
map.put("list",list);
return map;
}
}