Spring JdbcTemplate 示例

Spring JdbcTemplate 是 Spring JDBC包中最重要的类。

春天JDBcTemplate

  • JDBC生产出许多锅炉板码,如开通/关闭连接到数据库,处理sql例外等. 这使得代码极其繁琐并难以被读取. (_ _) * 在 [春季框架] (/community/touris/spring-framework) 中执行 JDBC 照顾到许多低级操作(打开/关闭连接,执行SQL查询等).
  • 因此,在与"春季框架"中的数据库合作时,我们只需要从数据库中定义连接参数并注册SQL查询,剩下的工作由"春季"完成. (_) ( )* 春季的JDBC有多个与数据库互动的类(几种方法). 其中最常见的是使用 " JdbcTemplate " 类。 这是管理所有事件和数据库连接的处理的基础类( ) ( )* JdbcTemplate 类执行 SQL 查询,在 ResultSet 上浏览,并检索到所谓的值, 更新指令和程序调用, 捕获 例外, 并将其转换为 `org.springframwork.dao' 包中定义的例外 。 () ( )* JdbcTemplate级的事例是线性安全的. 这意味着,通过配置JdbcTemplate类的单个实例,我们可以将其用于几个DAO对象.
  • 当使用JdbcTemplate时,最常被配置在Spring配置文件中. 之后,在DAO班中使用豆子来实施. ( (英语)

Jdbc 春季 示例

让我们看看春季JdbcTemplate示例程序. 我在这里使用Postgresql数据库,但你也可以使用任何其他关系数据库,如MySQL和Oracle。你所需要的只是更改数据库配置,它应该工作。

 1create table people (
 2id serial not null primary key,
 3first_name varchar(20) not null,
 4last_name varchar(20) not null,
 5age integer not null
 6);
 7
 8insert into people (id, first_name, last_name, age) values
 9(1, 'Vlad', 'Boyarskiy', 21),
10(2,'Oksi', ' Bahatskaya', 30),
11(3,'Vadim', ' Vadimich', 32);

Below image shows the final project structure in Eclipse. Spring JdbcTemplate Example

春季 JDBC Maven 依赖

我们需要遵循依赖 - spring-core, spring-context, spring-jdbcpostgresql. 如果您正在使用任何其他关系数据库,如MySQL,然后添加相应的Java驱动程序依赖。

 1<?xml version="1.0" encoding="UTF-8"?>
 2<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
 3    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4    <modelVersion>4.0.0</modelVersion>
 5
 6    <groupId>com.journaldev.spring</groupId>
 7    <artifactId>JdbcTemplate</artifactId>
 8    <version>1.0-SNAPSHOT</version>
 9    <properties>
10    	<spring.framework>4.3.0.RELEASE</spring.framework>
11    	<postgres.version>42.1.4</postgres.version>
12    </properties>
13    <dependencies>
14    	<dependency>
15    		<groupId>org.postgresql</groupId>
16    		<artifactId>postgresql</artifactId>
17    		<version>${postgres.version}</version>
18    	</dependency>
19    	<dependency>
20    		<groupId>org.springframework</groupId>
21    		<artifactId>spring-core</artifactId>
22    		<version>${spring.framework}</version>
23    	</dependency>
24    	<dependency>
25    		<groupId>org.springframework</groupId>
26    		<artifactId>spring-context</artifactId>
27    		<version>${spring.framework}</version>
28    	</dependency>
29    	<dependency>
30    		<groupId>org.springframework</groupId>
31    		<artifactId>spring-jdbc</artifactId>
32    		<version>${spring.framework}</version>
33    	</dependency>
34    </dependencies>
35
36</project>

春季数据源配置

下一步是创建春节配置类来定义DataSource标本. 我使用基于Java的配置,你也可以使用春节配置XML文件来做。

 1package com.journaldev.spring.config;
 2
 3import javax.sql.DataSource;
 4
 5import org.springframework.beans.factory.annotation.Autowired;
 6import org.springframework.context.annotation.Bean;
 7import org.springframework.context.annotation.ComponentScan;
 8import org.springframework.context.annotation.Configuration;
 9import org.springframework.context.annotation.PropertySource;
10import org.springframework.core.env.Environment;
11import org.springframework.jdbc.datasource.DriverManagerDataSource;
12
13@Configuration
14@ComponentScan("com.journaldev.spring")
15@PropertySource("classpath:database.properties")
16public class AppConfig {
17
18    @Autowired
19    Environment environment;
20
21    private final String URL = "url";
22    private final String USER = "dbuser";
23    private final String DRIVER = "driver";
24    private final String PASSWORD = "dbpassword";
25
26    @Bean
27    DataSource dataSource() {
28    	DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
29    	driverManagerDataSource.setUrl(environment.getProperty(URL));
30    	driverManagerDataSource.setUsername(environment.getProperty(USER));
31    	driverManagerDataSource.setPassword(environment.getProperty(PASSWORD));
32    	driverManagerDataSource.setDriverClassName(environment.getProperty(DRIVER));
33    	return driverManagerDataSource;
34    }
35}
  • @Configuration - 表示此类为 Spring 背景的配置
  • @ComponentScan("com.journaldev.spring") - 指定要扫描组件类的包
  • @PropertySource("classpath:database.properties") - 表示属性将从 database.properties 文件中读取

database.properties文件的内容如下所示。

1driver=org.postgresql.Driver
2url=jdbc:postgresql://127.0.0.1:5432/school
3dbuser=postgres
4dbpassword=postgres

如果您正在使用MySQL或其他关系数据库,请相应地更改上述配置。

春季JDBC模型班级

下一步是创建模型类来绘制我们的数据库表。

 1package com.journaldev.model;
 2
 3public class Person {
 4    private Long id;
 5    private Integer age;
 6    private String firstName;
 7    private String lastName;
 8
 9    public Person() {
10    }
11
12    public Person(Long id, Integer age, String firstName, String lastName) {
13    	this.id = id;
14    	this.age = age;
15    	this.firstName = firstName;
16    	this.lastName = lastName;
17    }
18
19    public Long getId() {
20    	return id;
21    }
22
23    public void setId(Long id) {
24    	this.id = id;
25    }
26
27    public Integer getAge() {
28    	return age;
29    }
30
31    public void setAge(Integer age) {
32    	this.age = age;
33    }
34
35    public String getFirstName() {
36    	return firstName;
37    }
38
39    public void setFirstName(String firstName) {
40    	this.firstName = firstName;
41    }
42
43    public String getLastName() {
44    	return lastName;
45    }
46
47    public void setLastName(String lastName) {
48    	this.lastName = lastName;
49    }
50
51    @Override
52    public String toString() {
53    	return "Person{" + "id=" + id + ", age=" + age + ", firstName='" + firstName + '\'' + ", lastName='" + lastName
54    			+ '\'' + '}';
55    }
56}

要从数据库中获取数据,我们需要实现接口 RowMapper. 这个接口只有一个方法 mapRow(ResultSet resultSet, int i),这将返回我们模型类的一个实例(即人)。

 1package com.journaldev.model;
 2
 3import java.sql.ResultSet;
 4import java.sql.SQLException;
 5
 6import org.springframework.jdbc.core.RowMapper;
 7
 8public class PersonMapper implements RowMapper<Person> {
 9
10    public Person mapRow(ResultSet resultSet, int i) throws SQLException {
11
12    	Person person = new Person();
13    	person.setId(resultSet.getLong("id"));
14    	person.setFirstName(resultSet.getString("first_name"));
15    	person.setLastName(resultSet.getString("last_name"));
16    	person.setAge(resultSet.getInt("age"));
17    	return person;
18    }
19}

JDBC DAO 春季课程

最后一步是创建 DAO 类以使用 sql 查询将我们的模型类绘制到数据库表,我们还将使用 `@Autowired' 注释配置 DataSource,并暴露一些 API。

 1package com.journaldev.spring.dao;
 2
 3import java.util.List;
 4
 5import com.journaldev.model.Person;
 6
 7public interface PersonDAO {
 8    Person getPersonById(Long id);
 9
10    List<Person> getAllPersons();
11
12    boolean deletePerson(Person person);
13
14    boolean updatePerson(Person person);
15
16    boolean createPerson(Person person);
17}
 1package com.journaldev.spring.dao;
 2
 3import java.util.List;
 4
 5import javax.sql.DataSource;
 6
 7import org.springframework.beans.factory.annotation.Autowired;
 8import org.springframework.jdbc.core.JdbcTemplate;
 9import org.springframework.stereotype.Component;
10
11import com.journaldev.model.Person;
12import com.journaldev.model.PersonMapper;
13
14@Component
15public class PersonDAOImpl implements PersonDAO {
16
17    JdbcTemplate jdbcTemplate;
18
19    private final String SQL_FIND_PERSON = "select * from people where id = ?";
20    private final String SQL_DELETE_PERSON = "delete from people where id = ?";
21    private final String SQL_UPDATE_PERSON = "update people set first_name = ?, last_name = ?, age  = ? where id = ?";
22    private final String SQL_GET_ALL = "select * from people";
23    private final String SQL_INSERT_PERSON = "insert into people(id, first_name, last_name, age) values(?,?,?,?)";
24
25    @Autowired
26    public PersonDAOImpl(DataSource dataSource) {
27    	jdbcTemplate = new JdbcTemplate(dataSource);
28    }
29
30    public Person getPersonById(Long id) {
31    	return jdbcTemplate.queryForObject(SQL_FIND_PERSON, new Object[] { id }, new PersonMapper());
32    }
33
34    public List<Person> getAllPersons() {
35    	return jdbcTemplate.query(SQL_GET_ALL, new PersonMapper());
36    }
37
38    public boolean deletePerson(Person person) {
39    	return jdbcTemplate.update(SQL_DELETE_PERSON, person.getId()) > 0;
40    }
41
42    public boolean updatePerson(Person person) {
43    	return jdbcTemplate.update(SQL_UPDATE_PERSON, person.getFirstName(), person.getLastName(), person.getAge(),
44    			person.getId()) > 0;
45    }
46
47    public boolean createPerson(Person person) {
48    	return jdbcTemplate.update(SQL_INSERT_PERSON, person.getId(), person.getFirstName(), person.getLastName(),
49    			person.getAge()) > 0;
50    }
51}

PersonDAOImpl类被注释为@Component,在这个类中,我们有一个类型的字段JdbcTemplate。当这个类的构建者被召唤时,将注入一个DataSource的实例,我们可以创建一个JdbcTemplate的实例。

春季JdbcTemplate测试计划

我们的 Spring JdbcTemplate 示例项目已经准备好了,让我们用测试类来测试。

 1package com.journaldev;
 2
 3import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4
 5import com.journaldev.model.Person;
 6import com.journaldev.spring.config.AppConfig;
 7import com.journaldev.spring.dao.PersonDAO;
 8
 9public class Main {
10    public static void main(String[] args) {
11    	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
12
13    	PersonDAO personDAO = context.getBean(PersonDAO.class);
14
15    	System.out.println("List of person is:");
16
17    	for (Person p : personDAO.getAllPersons()) {
18    		System.out.println(p);
19    	}
20
21    	System.out.println("\nGet person with ID 2");
22
23    	Person personById = personDAO.getPersonById(2L);
24    	System.out.println(personById);
25
26    	System.out.println("\nCreating person: ");
27    	Person person = new Person(4L, 36, "Sergey", "Emets");
28    	System.out.println(person);
29    	personDAO.createPerson(person);
30    	System.out.println("\nList of person is:");
31
32    	for (Person p : personDAO.getAllPersons()) {
33    		System.out.println(p);
34    	}
35
36    	System.out.println("\nDeleting person with ID 2");
37    	personDAO.deletePerson(personById);
38
39    	System.out.println("\nUpdate person with ID 4");
40
41    	Person pperson = personDAO.getPersonById(4L);
42    	pperson.setLastName("CHANGED");
43    	personDAO.updatePerson(pperson);
44
45    	System.out.println("\nList of person is:");
46    	for (Person p : personDAO.getAllPersons()) {
47    		System.out.println(p);
48    	}
49
50    	context.close();
51    }
52}

Below image shows the output produced when we execute above program. Output will vary based on sample data and on multiple executions, idea is to learn here how to use Spring JdbcTemplate through example program. Spring JDBC, Spring JdbcTemplate Example That's all about Spring JdbcTemplate, you can download the final project from below link.

下载春季JdbcTemplate示例项目

引用: API Doc

Published At
Categories with 技术
Tagged with
comments powered by Disqus