【问题标题】:One to many Spring Result Mapping一对多 Spring 结果映射
【发布时间】:2019-02-13 13:16:38
【问题描述】:

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

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 类)。

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

}

我想要达到的结果:

[
  {
    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 但我不知道如何实现它。提前致谢,祝您有美好的一天。

【问题讨论】:

  • 你是否在使用任何 ORM,如 hibernate 或 eclipselink?
  • 我真的不知道 orm 是什么,但我在 Eclipse-EE 中使用 Spring。

标签: java spring spring-boot jdbc


【解决方案1】:

这就是你的数据库的样子,你将创建 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);

希望这有帮助吗?

【讨论】:

    【解决方案2】:

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

    如果有人和我有同样的问题,我在这里找到了答案: multiple one-to-many relations ResultSetExtractor

    再次感谢大家,祝您有美好的一天。

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2012-04-27
      • 1970-01-01
      • 2021-08-22
      相关资源
      最近更新 更多