java - 一对多 Spring 结果映射

标签 java spring spring-boot jdbc

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

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

希望这有帮助吗?

关于java - 一对多 Spring 结果映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54671135/

相关文章:

java - Google Drive API 更改文件的所有权?

java - 创建 JUnit 测试时没有此类方法错误

java - 升级到 Spring Boot 2 时缺少 EnableOAuth2Sso 注释

java - 在 Spring Boot 中通过 RestTemplate 发布 JSON 对象

java - JVM 进程被终止时的 JMS onMessage 行为

java - 从 java 程序打开 outlook 邮件并将文件附加到目录中的邮件

java - 如何将数据绑定(bind)到 spring 表单中的列表

spring - 如何以编程方式为 Spring 中的集成测试填充测试数据?

java - Xml Jaxb 命名空间和属性顺序

java - Spring Integration 从 1.0.x 迁移到 2.2.6