当前位置: 代码迷 >> java >> 一对多Spring结果映射
  详细解决方案

一对多Spring结果映射

热度:86   发布时间:2023-07-31 10:59:13.0

这是我的第一次发帖问题,希望有人可以帮助我将结果映射到:

List<Clients>

因此,这是数据库的示例结果:

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

所以这是我的模式(java类)。

名称.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;
    }

}

我想要实现的结果:

[
  {
    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
]

我正在阅读ResultSetExtractor,但不知道如何实现。 在此先感谢,祝您有美好的一天。

这就是数据库的外观,您将创建4个表,分别是client,name,note,client_note。 client_note表应具有一对多关系的客户ID和便笺ID。 因此,如果您要获取ID为1的客户的所有备忘; 您的sql将如下所示

SELECT note_id FROM client_note WHERE clientId = 1;

然后您可以使用便签ID来查询便签表中的实际便签对象;

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);

希望这可以帮助?

我认为所有人都误解了我的问题,我不怪所有人。 我喜欢我的问题得到关注,并感谢所有向我提出建议的人。

如果有人遇到与我相同的问题,我在这里找到了答案:

再次感谢大家,祝您有愉快的一天。

  相关解决方案