Spring Data(二)|Spring Data JDBC实践之使用JDBC访问关系数据

参考官方文档:https://spring.io/guides/gs/relational-data-access
环境:IDEA、Java8、maven、springboot
实践内容:使用JDBC访问关系数据

pom.xml 配置文件的依赖:JDBC、H2内存数据库

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
    </dependencies>

首先创建一个实体类。

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);
    }
    // getters & setters omitted for brevity
}

然后创建一个主类。
此类中进行存储和检索数据:Spring提供了一个名为的模板类JdbcTemplate,可以轻松使用SQL关系数据库和JDBC。大多数JDBC代码都陷入资源获取、连接管理、异常处理和一般错误检查之中,这与代码要实现的内容完全无关。JdbcTemplate将负责这一切。

@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))");
        // Split up the array of whole names into an array of first/last names
        List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
                .map(name -> name.split(" "))
                .collect(Collectors.toList());
        // Use a Java 8 stream to print out each tuple of the list
        splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));
        // Uses JdbcTemplate's batchUpdate operation to bulk load data
        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。在这种情况下,没有任何。
  • 因为我们使用的是spring-jdbc,所以Spring Boot会自动创建一个JdbcTemplate对象,@Autowired注解标记的jdbcTemplate字段自动加载它并使其可用。
  • jdbcTemplate.batch()中使用?的参数,以避免SQL注入攻击通过指示JDBC来绑定变量。

启动运行
运行结果


ps:虚心求教。如果内容有误欢迎指出,如果内容帮助了你欢迎留下痕迹。

END

猜你喜欢

转载自blog.csdn.net/qq_32328959/article/details/88345389