# Spring `BeanPropertyRowMapper`教程

> 原文： [http://zetcode.com/spring/beanpropertyrowmapper/](http://zetcode.com/spring/beanpropertyrowmapper/)

Spring `BeanPropertyRowMapper`教程展示了如何使用`BeanPropertyRowMapper`将表行转换为指定 Bean 类的新实例。

Spring 是用于创建企业应用的流行 Java 应用框架。

## Spring `BeanPropertyRowMapper`

`BeanPropertyRowMapper`是`RowMapper`执行该表的行转换成指定的映射的目标类的一个新实例。 映射的目标类必须是顶级类，并且必须具有默认或无参数构造器。

## Spring `BeanPropertyRowMapper`示例

以下应用使用`BeanPropertyRowMapper`从`coutries`表中读取所有行。 在示例中，我们使用 MySQL 数据库。

`countries.sql`

```java
CREATE TABLE countries(id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255), population INT);

INSERT INTO countries(name, population) VALUES('China', 1382050000);
INSERT INTO countries(name, population) VALUES('India', 1313210000);
INSERT INTO countries(name, population) VALUES('USA', 324666000);
INSERT INTO countries(name, population) VALUES('Indonesia', 260581000);
INSERT INTO countries(name, population) VALUES('Brazil', 207221000);
INSERT INTO countries(name, population) VALUES('Pakistan', 196626000);
INSERT INTO countries(name, population) VALUES('Nigeria', 186988000);
INSERT INTO countries(name, population) VALUES('Bangladesh', 162099000);
INSERT INTO countries(name, population) VALUES('Nigeria', 186988000);
INSERT INTO countries(name, population) VALUES('Russia', 146838000);
INSERT INTO countries(name, population) VALUES('Japan', 126830000);
INSERT INTO countries(name, population) VALUES('Mexico', 122273000);
INSERT INTO countries(name, population) VALUES('Philippines', 103738000);

```

这是我们示例的一些测试数据。

```java
pom.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           ├───config
│   │           │       DBConfig.java
│   │           └───model
│   │                   Country.java
│   └───resources
│           db.properties
│           logback.xml
└───test
    └───java

```

这是项目结构。

`pom.xml`

```java
<?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>com.zetcode</groupId>
    <artifactId>springbeanpropertyrowmapperex</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <spring-version>5.1.3.RELEASE</spring-version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-version}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.6.0</version>
                <configuration>
                    <mainClass>com.zetcode.Application</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

```

在`pom.xml`文件中，我们声明了基本的 Spring 依赖关系。 `BeanPropertyRowMapper`是`spring-jdbc`的一部分。

`resources/db.properties`

```java
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mydb
jdbc.username=user7
jdbc.password=s$cret

```

我们在外部文件中具有基本的数据库属性。

`resources/logback.xml`

```java
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.zetcode" level="INFO"/>

    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <Pattern>%d{HH:mm:ss.SSS} [%thread] %blue(%-5level) %magenta(%logger{36}) - %msg %n
            </Pattern>
        </encoder>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="consoleAppender" />
    </root>
</configuration>

```

`logback.xml`是 Logback 日志库的配置文件。

`com/zetcode/model/Country.java`

```java
package com.zetcode.model;

import java.util.Objects;

public class Country {

    private Long id;
    private String name;
    private int population;

    public Country() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Country country = (Country) o;
        return population == country.population &&
                Objects.equals(id, country.id) &&
                Objects.equals(name, country.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, population);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Country{");
        sb.append("id=").append(id);
        sb.append(", name='").append(name).append('\'');
        sb.append(", population=").append(population);
        sb.append('}');
        return sb.toString();
    }
}

```

这是`Country` bean。 它具有`id`，`name`和`population`属性。

`com/zetcode/config/DBConfig.java`

```java
package com.zetcode.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

@Configuration
@PropertySource(value="classpath:db.properties", ignoreResourceNotFound=true)
public class DBConfig {

    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource() {

        var dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driver"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));

        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {

        var template = new JdbcTemplate();
        template.setDataSource(dataSource());

        return template;
    }
}

```

`DBConfig`配置`dataSource`和`jdbcTemplate` bean。 它从`db.properties`文件读取配置数据。

`com/zetcode/Application.java`

```java
package com.zetcode;

import com.zetcode.model.Country;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

@ComponentScan("com.zetcode")
public class Application {

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

    public static void main(String[] args) {

        var ctx = new AnnotationConfigApplicationContext(Application.class);
        var app = ctx.getBean(Application.class);

        app.run();

        ctx.close();
    }

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private void run() {

        var sql = "SELECT * FROM countries";

        var rowMapper = BeanPropertyRowMapper.newInstance(Country.class);
        var countries = jdbcTemplate.query(sql, rowMapper);

        countries.forEach(country -> logger.info("{}", country));
    }
}

```

这是主要的应用类。

```java
var sql = "SELECT * FROM countries";

```

我们定义一个查询以从`countries`表中检索所有行。

```java
var rowMapper = BeanPropertyRowMapper.newInstance(Country.class);

```

我们为`Country`类创建`BeanPropertyRowMapper`的新实例。

```java
var countries = jdbcTemplate.query(sql, rowMapper);

```

`JdbcTemplate`的`query()`执行 SQL 查询。 由于`BeanPropertyRowMapper`，表列自动映射到 bean 属性。

```java
$ mvn -q exec:java
12:47:37.079 INFO  com.zetcode.Application - Country{id=1, name='China', population=1382050000}
12:47:37.082 INFO  com.zetcode.Application - Country{id=2, name='India', population=1313210000}
12:47:37.083 INFO  com.zetcode.Application - Country{id=3, name='USA', population=324666000}
12:47:37.084 INFO  com.zetcode.Application - Country{id=4, name='Indonesia', population=260581000}
12:47:37.084 INFO  com.zetcode.Application - Country{id=5, name='Brazil', population=207221000}
12:47:37.085 INFO  com.zetcode.Application - Country{id=6, name='Pakistan', population=196626000}
12:47:37.086 INFO  com.zetcode.Application - Country{id=7, name='Nigeria', population=186988000}
12:47:37.087 INFO  com.zetcode.Application - Country{id=8, name='Bangladesh', population=162099000}
12:47:37.088 INFO  com.zetcode.Application - Country{id=9, name='Nigeria', population=186988000}
12:47:37.088 INFO  com.zetcode.Application - Country{id=10, name='Russia', population=146838000}
12:47:37.089 INFO  com.zetcode.Application - Country{id=11, name='Japan', population=126830000}
12:47:37.090 INFO  com.zetcode.Application - Country{id=12, name='Mexico', population=122273000}
12:47:37.090 INFO  com.zetcode.Application - Country{id=13, name='Philippines', population=103738000}

```

我们运行该应用。

在本教程中，我们使用`BeanPropertyRowMapper`将表行映射到 bean 属性。

您可能也对这些相关教程感兴趣：经典的 Spring 应用中的 [`JdbcTemplate`](/articles/springjdbctemplate/) ， [Spring HikariCP 教程](/articles/springhikaricp/)和 [Java 教程](/lang/java/)，或列出了[整个 Spring 教程](/all/#spring)。