You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过JDBC写入缓存后,如何用Java API读取并映射为自定义对象?

Reading Cached Data into Java Objects via Java API (JDBC Pre-Write)

Alright, let's break this down step by step—this is a super common scenario when working with cached databases and Java, so I’ll walk you through each part with concrete examples you can adapt to your setup.

First: Do you need a MyPerson class?

Short answer: Yes, absolutely. This class acts as a type-safe data transfer object (DTO) to hold cached data in a usable format within your Java app. Without it, you’d be stuck juggling raw ResultSet or cache entry objects, which is messy and error-prone.

Here’s a basic MyPerson example, assuming your Person table has columns id (INT), name (VARCHAR), age (INT), and email (VARCHAR):

public class MyPerson {
    private int id;
    private String name;
    private int age;
    private String email;

    // Getters and setters are required for mapping data into the class
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    // Optional: toString method for easy debugging
    @Override
    public String toString() {
        return "MyPerson{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                '}';
    }
}

Reading Cached Data into MyPerson Objects

Assuming you’re using a cache that exposes a native Java API (like Apache Ignite, Hazelcast, or even a JDBC-backed cache with a client), here’s how to query the cached Person table and map results to MyPerson objects.

Let’s use Apache Ignite as an example (the pattern translates to most caches with SQL support):

import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.query.SqlQuery;
import java.util.List;
import java.util.stream.Collectors;

public class CachePersonReader {
    public static void main(String[] args) {
        // Initialize the cache client (adjust this to your cache's configuration)
        try (Ignite ignite = Ignition.start()) {
            // Access the cached Person table (matches your DDL-created table)
            var personCache = ignite.cache("Person");

            // Execute a SQL query to fetch data (filter as needed, e.g., "WHERE age > 30")
            SqlQuery<?, ?> query = new SqlQuery<>(Object.class, "SELECT id, name, age, email FROM Person");
            
            // Fetch results and map them to MyPerson objects
            List<MyPerson> persons = personCache.query(query).getAll()
                    .stream()
                    .map(entry -> {
                        // Extract values from the cache entry's value list
                        var row = (List<Object>) entry.getValue();
                        MyPerson person = new MyPerson();
                        person.setId((int) row.get(0));
                        person.setName((String) row.get(1));
                        person.setAge((int) row.get(2));
                        person.setEmail((String) row.get(3));
                        return person;
                    })
                    .collect(Collectors.toList());

            // Use the mapped objects however you need
            persons.forEach(System.out::println);
        }
    }
}

If you’re using plain JDBC to read from the cache (some caches expose a JDBC driver), the mapping logic is nearly identical—you’ll just iterate over a ResultSet instead of cache entries:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class JdbcCacheReader {
    public static void main(String[] args) {
        // Adjust driver URL, username, and password to match your cache's JDBC setup
        String jdbcUrl = "jdbc:your-cache-driver-url";
        String user = "your-username";
        String pass = "your-password";

        try (Connection conn = DriverManager.getConnection(jdbcUrl, user, pass);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT id, name, age, email FROM Person")) {

            List<MyPerson> persons = new ArrayList<>();
            while (rs.next()) {
                MyPerson person = new MyPerson();
                person.setId(rs.getInt("id"));
                person.setName(rs.getString("name"));
                person.setAge(rs.getInt("age"));
                person.setEmail(rs.getString("email"));
                persons.add(person);
            }

            // Use the list of MyPerson objects
            persons.forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Handling Mismatched Fields Between MyPerson and Person Table

This is a common edge case—let’s cover both scenarios:

1. Partial Field Match (Some Fields Align, Others Don’t)

If MyPerson only includes a subset of the Person table’s columns (e.g., no email field), simply skip mapping the columns that don’t exist in your class. For example:

// MyPerson only has id, name, age
while (rs.next()) {
    MyPerson person = new MyPerson();
    person.setId(rs.getInt("id"));
    person.setName(rs.getString("name"));
    person.setAge(rs.getInt("age"));
    // Ignore the email column from the table entirely
    persons.add(person);
}

If MyPerson has extra fields not present in the table, leave them null or set default values—no changes to the cache table are needed.

2. Complete Field Mismatch (Different Names or Types)

If column names don’t align (e.g., table has full_name but class has name) or you need to calculate values (e.g., table stores birth_year but class uses age), manually map the values:

// Example: Person table has id, full_name, birth_year; MyPerson has id, name, age
while (rs.next()) {
    MyPerson person = new MyPerson();
    person.setId(rs.getInt("id"));
    // Map table's full_name to class's name field
    person.setName(rs.getString("full_name"));
    // Calculate age from birth_year instead of reading it directly
    int birthYear = rs.getInt("birth_year");
    int currentYear = java.time.LocalDate.now().getYear();
    person.setAge(currentYear - birthYear);
    persons.add(person);
}

Pro Tip: Simplify Mapping with Libraries

For larger classes or frequent mappings, libraries like Spring JDBC’s RowMapper or MapStruct can cut down boilerplate. Here’s a quick Spring RowMapper example:

import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;

RowMapper<MyPerson> personRowMapper = (rs, rowNum) -> {
    MyPerson person = new MyPerson();
    person.setId(rs.getInt("id"));
    person.setName(rs.getString("name"));
    person.setAge(rs.getInt("age"));
    return person;
};

// Use with Spring's JdbcTemplate
List<MyPerson> persons = jdbcTemplate.query("SELECT * FROM Person", personRowMapper);

内容的提问来源于stack exchange,提问作者aryndin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:19:35