In Java - How to map resultSet into a complex object?

前端 未结 4 1245
生来不讨喜
生来不讨喜 2021-01-24 02:12

How can I map a resultset from a few tables into a complex object? let me elaborate:

Lets say I have these 2 classes:

public class User {
    private int         


        
相关标签:
4条回答
  • 2021-01-24 02:38

    ORM libraries will do want you describe. Although most will likely perform 2 queries instead of a join. Usually you need to provide some kind of annotation on the list field so that it knows how to perform the query:

    public class Country{
      private String country;
    
      @OneToMany(...)
      private ArrayList<User> users;
    }
    

    When you select a Country object the ORM selects all related User objects and adds them into the users ArrayList.

    The library that I use is sormula (I am the author). See the one to many example. No annotations are required if foreign key in User class is same name as primary key in Country class.

    This page has good information about JPA OneToMany annotation: en.wikibooks.org/wiki/Java_Persistence/OneToMany

    0 讨论(0)
  • 2021-01-24 02:48

    Create a HashMap of where user id is the key, and user is the value. Then when you process the result set, do map.get(resultset.get(userid)), if it's null, create a new user, but if it isn't then do the logic to append a user to the country.

    HashMap<Integer, User> users;
    HashMap<String, Country> countries;
    //inside the result set processing
    User u = users.get(resultSet.get("id"));
        if(null != u) {
          //populate user here
        } else {
           Country c = countries.get(resultSet.get(country);
           c.users.add(u);
        }
    
    0 讨论(0)
  • 2021-01-24 02:53

    When using jdbcTemplate of springframework, to implement the RowMapper interface is a good way.

    0 讨论(0)
  • 2021-01-24 02:56

    Maybe try something like this:

    ArrayList<User> users = new ArrayList<User>();
    while(resultSet.next)
    {
         users.add(new User(resultSet.getString("id"), resultSet.getString("fname"), resultSet.getString("lname"));
         //you can also add your countries to an array list
    }
    
    0 讨论(0)
提交回复
热议问题