1、使用JDBC
1)在pom文件中导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2)配置文件
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.15.22:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
效果:
默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源;
数据源的相关配置都在DataSourceProperties里面;
2、使用Druid数据库连接池
1)pom文件
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
2)配置文件
#使用Druid数据源
spring:
datasource:
druid:
url: jdbc:mysql://localhost:3306/exam
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
3、容易出现bug的地方
1)在配置文件中要添加mapper文件扫描
# 扫描mapper文件
mybatis:
mapper-locations: classpath:mapper/*.xml
2)扫描dao包
第一种方式:在SpringBoot的主启动类上添加注解@MapperScan,(括号内指定自己的dao包)。这种方式只用添加一次。
@SpringBootApplication
@MapperScan("com.lyq.dao")
public class SpringBootMain {
public static void main(String[] args) {
SpringApplication.run(SpringBootMain.class,args);
}
}
第二种方式:在dao接口上添加@Mapper注解。这种方式需要在每一个dao接口上添加注解
@Mapper
public interface UsersDao{
List<Users> getAllUser();
}