参考官方文档:https://spring.io/guides/gs/relational-data-access
环境:IDEA、Java8、maven、springboot
实践内容:使用JDBC访问关系数据
pom.xml 配置文件的依赖:JDBC、H2内存数据库
org.springframework.boot
spring-boot-starter-jdbc
com.h2database
h2
首先创建一个实体类。
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
ps:虚心求教。如果内容有误欢迎指出,如果内容帮助了你欢迎留下痕迹。