这是我第一次发布问题,希望有人可以帮助我将结果映射到:
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/