spring cloud初学者--使用数据库

今天我们来看看springcloud连接关系型数据库处理数据

创建项目

创建pom文件

<?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>org.springframework</groupId>
    <artifactId>gs-relational-data-access</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <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>
  • 收集类路径上的所有jar,并构建一个可运行的jar,这样可以更方便地执行和运输您的服务
  • 它搜索public static void main()方法来标记为可运行类
  • 它提供了一个内置的依赖解析器,它将版本号设置为与Spring Boot依赖关系相匹配。您可以覆盖任何您想要的版本,但它将默认为Boot所选择的一组版本(就是所有和springBoot有依赖的jar都不需要版本号)

代码

为了创建一个实体类,用来接收从数据库查出来的数据

package hello;

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);
    }
}

spring提供了一个jdbcTemplate,他能非常简单的连接数据库,让我们更方便的连接数据库,执行sql。大多数JDBC代码都涉及资源获取,连接管理,异常处理以及与代码实现完全无关的一般错误检查,而spring的jdbcTemplate能很好的让我们关注我们的业务,而不必关系其他的事情。

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;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@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, args);
    }

    @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());

        // 利用jdk8,打印日志
        splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));

        // 利用jdbcTemplate插入数据,并且查询出答应的日志
        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()));
    }
}

@SpringBootApplication是一个方便的注释,它添加以下所有内容:
@Configuration将该类标记为应用程序上下文的bean定义的源。 @EnableAutoConfiguration指示Spring Boot根据类路径设置,其他bean和各种属性设置开始添加bean。
@ComponentScan告诉Spring在hello包中寻找其他组件,配置和服务。 在这种情况下,没有任何服务需要寻找
他的main()方法使用Spring Boot的SpringApplication.run()方法启动应用程序。你注意到没有一行XML吗?没有web.xml文件。

执行结果

  main] hello.Application                        : query customer
2017-07-01 11:26:10.673  INFO 43286 --- [           main] hello.Application                        : customer:Customer[id=3, firstName='Josh', lastName='Bloch']
2017-07-01 11:26:10.673  INFO 43286 --- [           main] hello.Application                        : customer:Customer[id=4, firstName='Josh', lastName='Long']
2017-07-01 11:26:10.675  INFO 43286 --- [           main] hello.Application                        : Started Application in 11.56 seconds (JVM running for 12.177)

连接生产数据库

嵌入式数据库

嵌入式数据库通常用于开发和测试环境,不推荐用于生产环境。Spring Boot提供自动配置的嵌入式数据库有H2、HSQL、Derby,你不需要提供任何连接配置就能使用。例如我上边使用了

  <dependency>
         <groupId>com.h2database</groupId>
         <artifactId>h2</artifactId>
  </dependency>

而我们要使用我们的声场数据库,例如mysql的数据库,则需要加上MySQL的驱动,把h2的换成

  <dependency>
          <groupId>com.h2database</groupId>
          <artifactId>h2</artifactId>
  </dependency>

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

spring.datasource.url=jdbc:mysql://localhost:3306/account_center
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

使用JdbcTemplate操作数据库

@SpringBootApplication
public class Application implements CommandLineRunner {

    private final static Logger log = LoggerFactory.getLogger(Application.class);


    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... strings) throws Exception {

       create("menghaibin", "haizeiwang");

        System.out.println(getAllUsers());

    }


    public void create(String name, String content) {
        jdbcTemplate.update("insert into test001(name, content) values(?, ?)", name, content);
    }

    public Integer getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from test001", Integer.class);
    }
}

这样我们就会发现我们的生产数据库就能顺利的插入数据。

小结

通过这些程序,我们可以发现,我们可以很容易的执行一些业务操作,而且这些操作并没有我们所发现的一些创建数据源,连接池之类的,而是直接执行业务操作

发布了176 篇原创文章 · 获赞 84 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/lovemenghaibin/article/details/73865096
今日推荐