本文讲解 Spring Boot 基础下,如何使用 JDBC,配置数据源和通过 JdbcTemplate 编写数据访问。
首先在pom.xml中引入jdbc依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
复制代码
添加MySql依赖
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.43</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.3</version></dependency>
复制代码
在src/main/resources/application.properties中配置数据源信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3307/springboot
spring.datasource.username=root
spring.datasource.password=root
复制代码
运行数据库脚本
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;USE `springboot`;DROP TABLE IF EXISTS `t_author`;CREATE TABLE `t_author` (`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',`name` varchar(32) NOT NULL COMMENT '测试名称',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
复制代码
创建实体对象
public class Author {private long id;//用户ID.private String name;//测试名称.// SET和GET方法
}
复制代码
Controller层
@RestController
@RequestMapping(value="/data/jdbc/author")
public class DemoController {@Autowiredprivate AuthorService AuthorService;/*** 新增方法*/@RequestMapping(method = RequestMethod.POST)public void add(@RequestBody JSONObject jsonObject) {String id = jsonObject.getString("id");String name = jsonObject.getString("name");Author author = new Author();if (author!=null) {author.setId(Long.valueOf(id));}author.setName(name);try{this.authorService.add(author);}catch(Exception e){e.printStackTrace();throw new RuntimeException("新增错误");}}
复制代码
Service层
public interface BaseAuthorService {int add(Author author);
}
复制代码
service实现类
@Service
public class AuthorService implements BaseAuthorService {@Autowiredprivate AuthorDao authorDao;public Demo add(Long id){return authorDao.add(id);}}
复制代码
DAO层
public interface BaseAuthorDao {int add(Author author);
}
复制代码
Dao层实现类
@Repository
public class AuthorDao implements BaseAuthorDao {@Autowiredprivate AuthorDao authorDao;@Overridepublic int add(Author author) {return authorDao.add(author);}
}
复制代码
上面介绍的JdbcTemplate只是最基本的添加操作,更多使用方法请参考:JdbcTemplate API
在Spring Boot中使用Jdbc访问数据库依旧秉持Spring Boot框架的特点:简单。
我们只需要在pom.xml中加入数据库依赖,再到application.properties中配置连接信息,不需要像Spring应用中创建JdbcTemplate的Bean,就可以直接在自己的对象中注入使用。
感谢你花时间读到结尾!:D
后端一枚,默默搬砖撸代码,如果觉得不错欢迎关注我的公众号