springboot---数据整合篇

本文讲解 Spring Boot 基础下,如何使用 JDBC,配置数据源和通过 JdbcTemplate 编写数据访问。

环境依赖

修改 POM 文件,添加spring-boot-starter-jdbc依赖。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-jdbc</artifactId>
  4. </dependency>

添加mysql依赖。

  1. <dependency>
  2. <groupId>mysql</groupId>
  3. <artifactId>mysql-connector-java</artifactId>
  4. <version>5.1.35</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>druid</artifactId>
  9. <version>1.0.14</version>
  10. </dependency>

数据源

方案一 使用 Spring Boot 默认配置

使用 Spring Boot 默认配置,不需要在创建 dataSource 和 jdbcTemplate 的 Bean。

src/main/resources/application.properties 中配置数据源信息。

  1. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  2. spring.datasource.url=jdbc:mysql://localhost:3307/springboot_db
  3. spring.datasource.username=root
  4. spring.datasource.password=root

方案二 手动创建

src/main/resources/config/source.properties 中配置数据源信息。

  1. # mysql
  2. source.driverClassName = com.mysql.jdbc.Driver
  3. source.url = jdbc:mysql://localhost:3306/springboot_db
  4. source.username = root
  5. source.password = root

通过 Java Config 创建 dataSource 和jdbcTemplate。

  1. @Configuration
  2. @EnableTransactionManagement
  3. @PropertySource(value = {"classpath:config/source.properties"})
  4. public class BeanConfig {
  5.  
  6. @Autowired
  7. private Environment env;
  8.  
  9. @Bean(destroyMethod = "close")
  10. public DataSource dataSource() {
  11. DruidDataSource dataSource = new DruidDataSource();
  12. dataSource.setDriverClassName(env.getProperty("source.driverClassName").trim());
  13. dataSource.setUrl(env.getProperty("source.url").trim());
  14. dataSource.setUsername(env.getProperty("source.username").trim());
  15. dataSource.setPassword(env.getProperty("source.password").trim());
  16. return dataSource;
  17. }
  18.  
  19. @Bean
  20. public JdbcTemplate jdbcTemplate() {
  21. JdbcTemplate jdbcTemplate = new JdbcTemplate();
  22. jdbcTemplate.setDataSource(dataSource());
  23. return jdbcTemplate;
  24. }
  25. }

脚本初始化

先初始化需要用到的SQL脚本。

  1. CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
  2.  
  3. USE `springboot_db`;
  4.  
  5. DROP TABLE IF EXISTS `t_author`;
  6.  
  7. CREATE TABLE `t_author` (
  8. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  9. `real_name` varchar(32) NOT NULL COMMENT '用户名称',
  10. `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
  11. PRIMARY KEY (`id`)
  12. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

使用JdbcTemplate操作

实体对象

  1. public class Author {
  2. private Long id;
  3. private String realName;
  4. private String nickName;
  5. // SET和GET方法
  6. }

DAO相关

  1. public interface AuthorDao {
  2. int add(Author author);
  3. int update(Author author);
  4. int delete(Long id);
  5. Author findAuthor(Long id);
  6. List<Author> findAuthorList();
  7. }

我们来定义实现类,通过JdbcTemplate定义的数据访问操作。

  1. @Repository
  2. public class AuthorDaoImpl implements AuthorDao {
  3.  
  4. @Autowired
  5. private JdbcTemplate jdbcTemplate;
  6.  
  7. @Override
  8. public int add(Author author) {
  9. return jdbcTemplate.update("insert into t_author(real_name, nick_name) values(?, ?)",
  10. author.getRealName(), author.getNickName());
  11. }
  12.  
  13. @Override
  14. public int update(Author author) {
  15. return jdbcTemplate.update("update t_author set real_name = ?, nick_name = ? where id = ?",
  16. new Object[]{author.getRealName(), author.getNickName(), author.getId()});
  17. }
  18.  
  19. @Override
  20. public int delete(Long id) {
  21. return jdbcTemplate.update("delete from t_author where id = ?", id);
  22. }
  23.  
  24. @Override
  25. public Author findAuthor(Long id) {
  26. List<Author> list = jdbcTemplate.query("select * from t_author where id = ?", new Object[]{id}, new BeanPropertyRowMapper(Author.class));
  27. if(null != list && list.size()>0){
  28. Author auhtor = list.get(0);
  29. return auhtor;
  30. }else{
  31. return null;
  32. }
  33. }
  34. @Override
  35. public List<Author> findAuthorList() {
  36. List<Author> list = jdbcTemplate.query("select * from t_author", new Object[]{}, new BeanPropertyRowMapper<Author>(Author.class));
  37. return list;
  38. }
  39. }

Service相关

  1. public interface AuthorService {
  2. int add(Author author);
  3. int update(Author author);
  4. int delete(Long id);
  5. Author findAuthor(Long id);
  6. List<Author> findAuthorList();
  7. }

我们来定义实现类,Service层调用Dao层的方法,这个是典型的套路。

  1. @Service("authorService")
  2. public class AuthorServiceImpl implements AuthorService {
  3. @Autowired
  4. private AuthorDao authorDao;
  5.  
  6. @Override
  7. public int add(Author author) {
  8. return this.authorDao.add(author);
  9. }
  10.  
  11. @Override
  12. public int update(Author author) {
  13. return this.authorDao.update(author);
  14. }
  15.  
  16. @Override
  17. public int delete(Long id) {
  18. return this.authorDao.delete(id);
  19. }
  20.  
  21. @Override
  22. public Author findAuthor(Long id) {
  23. return this.authorDao.findAuthor(id);
  24. }
  25.  
  26. @Override
  27. public List<Author> findAuthorList() {
  28. return this.authorDao.findAuthorList();
  29. }
  30. }

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  1. @RestController
  2. @RequestMapping(value="/data/jdbc/author")
  3. public class AuthorController {
  4. @Autowired
  5. private AuthorService authorService;
  6. /**
  7. * 查询用户列表
  8. */
  9. @RequestMapping(method = RequestMethod.GET)
  10. public Map<String,Object> getAuthorList(HttpServletRequest request) {
  11. List<Author> authorList = this.authorService.findAuthorList();
  12. Map<String,Object> param = new HashMap<String,Object>();
  13. param.put("total", authorList.size());
  14. param.put("rows", authorList);
  15. return param;
  16. }
  17. /**
  18. * 查询用户信息
  19. */
  20. @RequestMapping(value = "/{userId:\d+}", method = RequestMethod.GET)
  21. public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
  22. Author author = this.authorService.findAuthor(userId);
  23. if(author == null){
  24. throw new RuntimeException("查询错误");
  25. }
  26. return author;
  27. }
  28.  
  29. /**
  30. * 新增方法
  31. */
  32. @RequestMapping(method = RequestMethod.POST)
  33. public void add(@RequestBody JSONObject jsonObject) {
  34. String userId = jsonObject.getString("user_id");
  35. String realName = jsonObject.getString("real_name");
  36. String nickName = jsonObject.getString("nick_name");
  37. Author author = new Author();
  38. if (author!=null) {
  39. author.setId(Long.valueOf(userId));
  40. }
  41. author.setRealName(realName);
  42. author.setNickName(nickName);
  43. try{
  44. this.authorService.add(author);
  45. }catch(Exception e){
  46. e.printStackTrace();
  47. throw new RuntimeException("新增错误");
  48. }
  49. }
  50. /**
  51. * 更新方法
  52. */
  53. @RequestMapping(value = "/{userId:\d+}", method = RequestMethod.PUT)
  54. public void update(@PathVariable Long userId, @RequestBody JSONObject jsonObject) {
  55. Author author = this.authorService.findAuthor(userId);
  56. String realName = jsonObject.getString("real_name");
  57. String nickName = jsonObject.getString("nick_name");
  58. author.setRealName(realName);
  59. author.setNickName(nickName);
  60. try{
  61. this.authorService.update(author);
  62. }catch(Exception e){
  63. e.printStackTrace();
  64. throw new RuntimeException("更新错误");
  65. }
  66. }
  67. /**
  68. * 删除方法
  69. */
  70. @RequestMapping(value = "/{userId:\d+}", method = RequestMethod.DELETE)
  71. public void delete(@PathVariable Long userId) {
  72. try{
  73. this.authorService.delete(userId);
  74. }catch(Exception e){
  75. throw new RuntimeException("删除错误");
  76. }
  77. }
  78. }

总结

通过,上面这个简单的案例,我们发现 Spring Boot 仍然秉承了 Spring 框架的一贯套路,并简化 Spring 应用的初始搭建以及开发过程。

原文地址:https://www.cnblogs.com/wirr/p/8989035.html