Java Web基础入门( 五 )

mysql> delete from room where id = 2;Query OK, 1 row affected (0.01 sec)mysql> select * from room;+----+--------+---------+-------------+-------------+| id | name| comment | create_date | update_date |+----+--------+---------+-------------+-------------+|1 | 大床房 | 无窗| 2017-11-26| 2017-11-26|+----+--------+---------+-------------+-------------+1 row in set (0.00 sec)
到此,增删改查语句复习完毕 。开始引入项目 。
项目连接MySQL
保持MySQL打开状态 。
引入mysql驱动和-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-8spring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driver
新建com.test.demo..
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;@Configurationpublic class DBConfiguration {@Beanpublic JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DataSource dataSource) {return new JdbcTemplate(dataSource);}}
下面写一个测试来测试是否联通了 。在src/test/java下,新建com.test.demo..
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 {@Autowiredprivate JdbcTemplate jdbcTemplate;@Testpublic void testSelect() {List maps = jdbcTemplate.queryForList("select * from room");System.out.println(maps);}}
控制太打印出刚才的数据库中的数据:
[{id=1, name=大床房, comment=无窗, create_date=2017-11-26, update_date=2017-11-26}]
【Java Web基础入门】 分层架构 DI 面向接口编程 编写测试 集成CI 登陆拦截 .0 事物 JPA 缓存 远程调用 参考