继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Java Web基础入门,Springboot入门(9)

RyanMiao
关注TA
已关注
手记 10
粉丝 56
获赞 133

前言

语言都是相通的,只要搞清楚概念后就可以编写代码了。而概念是需要学习成本的。

本文首发于博客园-Ryan Miao. 由于限制2000字,只能分多篇。

项目连接MySQL

保持MySQL打开状态。

引入mysql驱动和spring-jdbc

compile("org.springframework.boot:spring-boot-starter-jdbc")
compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'

修改配置文件,新增:

spring.datasource.url=jdbc:mysql://localhost:3306/springboot_demo?serverTimezone=UTC&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

新建com.test.demo.config.DBConfiguration

package com.test.demo.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class DBConfiguration {

    @Bean
    public JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
  1. @Configuration 标注这个类是一个配置类,spring会自动扫描这个注解,将里面的配置运行。
  2. @Bean 标注声明一个Bean,由spring管理,在需要的地方注入。
  3. @Qualifier("dataSource") @Bean的参数列表中对象会从spring容器中查找bean,找到后注入参数。而Qualifier则声明要注入的bean的name或者id是什么,这在spring容器包含2个以上同类型的bean的时候有用。
  4. DataSource 这个对象是springboot自动创建的,通过扫描配置类里的配置,当检测到有配置datasource的时候会创建这个bean。于是,在这里就可以注入了,即我们配置的那几个属性。
  5. JdbcTemplate 一个封装了对DB操作的library, 通过它来对数据库操作。

下面写一个测试来测试是否联通了。在src/test/java下,新建com.test.demo.config.DBConfigurationTest

package com.test.demo.config;

import com.test.demo.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
@Import({Application.class, DBConfiguration.class})
public class DBConfigurationTest {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void testSelect() {

        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from room");
        System.out.println(maps);
    }
}

控制太打印出刚才的数据库中的数据:

[{id=1, name=大床房, comment=无窗, create_date=2017-11-26, update_date=2017-11-26}]
  1. @RunWith(SpringRunner.class)运行spring容器的测试
  2. @SpringBootTest springboot测试
  3. @Import({Application.class, DBConfiguration.class}) 导入我们需要的配置
  4. @Autowired自动注入属性,刚才在Configuration中声明了一个Bean,在这里通过这个注解获取那个bean
  5. @Test 这是一个JUnit测试

下一篇,简单使用JDBCTemplate

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP