简体   繁体   中英

One to many Spring Result Mapping

This is my first time posting problem hope someone can help me on this mapping the result into:

List<Clients>

So here's the sample result from database:

NameID   |  Name      | Notes                  | Date
1        | Client1    | Get this on monday.    | null
1        | Client1    | Get this on wednesday. | null
2        | Client2    | Meet on saturday.      | null

So here's my mode (java class).

Name.java

private int NameId;
private String ClientName;
.. getter and setter

Notes.java

private int NotesId;
private String ClientNote;
.. getter and setter

Clients.java

private Name name;
private List<Notes> notes;
.. getter and setter

ClientResultSet.java

class ClientResultSet implements ResultSetExtractor<List<Clients>>{

    @Override
    public List<Clients> extractData(ResultSet rs) throws SQLException, DataAccessException {
        Map<int, Clients> map = new HashMap<int, Clients>();
        while(rs.next()) {
            int NameId= rs.getInt("NameId");
            Clients clients= map.get(contactId);

            if (clients== null) {

                // I'm losing my thoughts here. :'(
            }
        }
        return null;
    }

}

Result I want to achieve:

[
  {
    name:{
      NameId: 1,
      Name: "Client1"
    },
    notes[
      {
         NotesId: 1,
         ClientNote: "Get this on monday",
         Date: null
      },
      {
         NoteId: 2,
         ClientNote: "Get this on wednesday",
         Date: null
      }
    ]
  },
  {
    name:{},
    notes:[{},{}]
  }
  ... and so on
]

I'm reading ResultSetExtractor but I don't know how to implement it. Thanks in advance and have a good day.

This is how your database should look like, you will create 4 tables, client, name, note, client_note. the client_note table should have the client id and the note id for one to many relationship. so if you want to get all notes for a client with an id of 1; your sql will look like this

SELECT note_id FROM client_note WHERE clientId = 1;

then you can use the note id's you get to query the note table for the actual note objects;

client
   int id;
   int nameId (foreignKey referencing name.id);

name
   int id;
   String ClientName;

note
   int id;
   String ClientNote;

client_note
    int id;
    int clientId  (foreignKey referencing client.id);
    int noteId  (foreignKey referencing note.id);

Hope this helps?

I think everyone misunderstood my question and I don't blame everyone. I love that my question gets notice and I thank everyone who gave their suggestion to me.

I found the answer here if anyone have the same problem as me: multiple one-to-many relations ResultSetExtractor

Again, thank you everyone and have a nice day.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM