如何将 ResulSet 的多个值放入 Java 个对象中

How to get ResulSet multiple values into Java objects

我有 2 个表 Person (Person_id, name)Address(Address_id, Person_idAd, addressName) 具有一对多关系。

通过以下查询我得到

String query = "SELECT Person_id, addressName from Person, Address where Person_id = Person_idAd"
        
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
        
}
Person_id 地址名称
1001 地址-1
1001 地址 2
1002 地址-1

我想将此条目映射到 Java 个对象。

class Person {
    int id;
    ArrayList<String> addresses;
    // get and set...
}

请告诉我如何完成。
谢谢。

您需要在 while

内构建类似这样的对象
Person person = null;
List<String> addrList = new ArrayList<String>();
while (rs.next()) {
int id = rs.getXXX() //you will personid 

if(person==null) {
   person = new Person();
   person.setId(id);
   addrList.add(rs.getXXX);
   person.setAddresses(addrList);
} else if(id!=person.getId()) {
  person = new Person();
   person.setId(id);
   addrList.add(rs.getXXX);
   person.setAddresses(addrList);
}
}

首先,将 ORDER BY Person_id 添加到 [SQL] 查询中。
此外,您的 [SQL] 查询应使用 JOIN.

select P.PERSON_ID, A.ADDRESSNAME
  from PERSON P
  join ADDRESS A
    on P.PERSON_ID = A.PERSON_IDAD
 order by P.PERSON_ID

每当 PERSON_ID 发生变化时,创建一个新的 Person 对象并设置 id 成员。
PERSON_ID 保持不变的同时,将所有地址收集到 java.util.List.
你可能还想要另一个 java.util.List 来容纳所有的人。

java.util.List<Person> people = new java.util.ArrayList<>();
int currentId = 0; // Assuming there is no such ID.
int id;
Person person = null;
java.util.List<String> addresses;
while (rs.next()) {
    id = rs.getInt(1);
    if (id != currentId) {
        if (person != null) {
            person.setAddresses(addresses);
            people.add(person);
        }
        person = new Person();
        person.setId(id);
        currentId = id;
        addresses = new java.util.ArrayList<>();
    }
    addresses.add(rs.getString(2));
}
// Add the last person.
if (person != null) {
    person.setAddresses(addresses);
    people.add(person);
}

当然,作为替代方案,如果相关,您可以使用 Object Relational Mapping (ORM) tool like Hibernate.