1.pom.xml文件配置
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId> <artifactId>jdbc</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <!--引入jdbc支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--引入嵌入式数据库支持h2,springboot提供自动配置的嵌入式数据库有h2,hsql,derby,即不需要提供任何连接配置就能使用--> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
我们在pom文件里可以看到,com.h2database这个库起作用的范围是runtime,也就是说,当应用程序启动时,如果Spring Boot在classpath下检测到org.h2.Driver的存在,会自动配置H2数据库连接。现在启动应用程序来观察,以验证我们的想法。
2.实体类Customer.java文件
package hello;
/**
* Created by guanguan on 17/6/1.
*/
public class Customer {
private long id;
private String firstName, lastName;
public Customer(long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString(){
return String.format("Customer[id=%d,firstName='%s',lastName='%s']",id,firstName,lastName);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
3.Application.java文件,为应用程序的入口文件,负责程序启动以及一些基础性的工作。
package hello;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* Created by guanguan on 17/6/1.
*/
@SpringBootApplication
public class Application implements CommandLineRunner{
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public void run(String... strings) throws Exception{
log.info("creating tables;");
jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
jdbcTemplate.execute("CREATE TABLE customers (id SERIAL,first_name VARCHAR(255),last_name VARCHAR(255))");
List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
.map(name -> name.split(" "))
.collect(Collectors.toList());
splitUpNames.forEach(name->log.info(String.format("Inserting customer record for %s,%s",name[0],name[1])));
jdbcTemplate.batchUpdate("INSERT INTO customers(first_name,last_name) VALUES (?,?)",splitUpNames);
log.info("Querying for customer records where first_name='Josh':");
jdbcTemplate.query(
"SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[] { "Josh" },
(rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
).forEach(customer -> log.info(customer.toString()));
}
}
运行结果:
2017-06-02 10:40:54.671 INFO 13599 --- [ main] hello.Application : creating tables---1;
2017-06-02 10:40:54.845 INFO 13599 --- [ main] hello.Application : Inserting customer record for John,Woo
2017-06-02 10:40:54.845 INFO 13599 --- [ main] hello.Application : Inserting customer record for Jeff,Dean
2017-06-02 10:40:54.845 INFO 13599 --- [ main] hello.Application : Inserting customer record for Josh,Bloch
2017-06-02 10:40:54.845 INFO 13599 --- [ main] hello.Application : Inserting customer record for Josh,Long
2017-06-02 10:40:54.890 INFO 13599 --- [ main] hello.Application : Querying for customer records where first_name='Josh':
2017-06-02 10:40:54.896 INFO 13599 --- [ main] hello.Application : Customer[id=3,firstName='Josh',lastName='Bloch']
2017-06-02 10:40:54.896 INFO 13599 --- [ main] hello.Application : Customer[id=4,firstName='Josh',lastName='Long']
2017-06-02 10:40:54.898 INFO 13599 --- [ main] hello.Application : Started Application in 2.847 seconds (JVM running for 3.539)
2017-06-02 10:40:54.901 INFO 13599 --- [ Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f8f5f62: startup date [Fri Jun 02 10:40:52 CST 2017]; root of context hierarchy
2017-06-02 10:40:54.907 INFO 13599 --- [ Thread-2] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
Process finished with exit code 0
==============================================================================3.如果是自定义的数据库
pom.xml文件
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
连接生产数据库/src/main/resources/application.yml文件
spring:
datasource:
url: jdbc:mysql://127.0.0.1/test
username: root
password: 123456
driverClassName: com.mysql.jdbc.Driver