添加数据库信息
该数据库下创建名为t_table的表,并添加模拟字段,脚本如下:
DROP TABLE IF EXISTS `t_table`;
CREATE TABLE `t_table` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`real_name` varchar(32) NOT NULL COMMENT '用户名称',
`live_address` varchar(32) NOT NULL COMMENT '用户居住地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
数据库创建完成,下面开始介绍数据库连接的几种集成方式。
配置文件信息(yml / properties)
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/springboot_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false
driverClassName: com.mysql.jdbc.Driver
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
注意:配置文件会因为依赖的不完整而导致报红,所以建议先添加maven依赖。
一 集成JdbcTemplate
添加Maven依赖
<!--添加MySql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<!--JDBC连接数据库-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
创建实体类(entity)
public class TableEntity {
private Long id;
private String realName;
private String liveAddress;
public TableEntity() { }
public TableEntity(Long id, String realName, String liveAddress) {
this.id = id;
this.realName = realName;
this.liveAddress = liveAddress;
}
// get | set
}
创建接口(Dao)
public interface TableDao {
//添加
int add(TableEntity tableEntity);
}
实现接口(serviceÿ