This guide walks you through the process of accessing relational data with Spring.
You will build an application that uses Spring’s JdbcTemplate
to access data stored in a relational database.
1 创建新项目
2 创建实体类
The simple data access logic you will work with manages the first and last names of customers. To represent this data at the application level, create a Customer class.
package com.example.relationaldataaccess;
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
}
3 存储和检索数据
Spring provides a template class called JdbcTemplate
that makes it easy to work with SQL relational databases and JDBC
.
Most JDBC code is mired in resource acquisition, connection management, exception handing, and general error checking that is wholly unrelated to what the code is meant to achieve.
The JdbcTemplate takes care of all of that for you. All y