java - 一对多 Spring 结果映射
问题描述
这是我第一次发布问题希望有人可以帮助我将结果映射到:
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
客户端.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);
希望这可以帮助?
推荐阅读
- javascript - KML 和谷歌地图:加载值的问题
进入弹出窗口 - android - 如何使用intent在android中打开后置/后置摄像头
- xpages - 编译 Xpages 的 java 脚本库中的错误
- javascript - 遍历 JSON 并获取每个数据键的图像
- javascript - 使用 replace 和 pathArray[0],我似乎是在添加而不是用我的 JavaScript 替换
- vba - 如何传递电子邮件地址和密码以在 GMail 中创建电子邮件?
- regex - Pyspark - 正则表达式 - 从最后一个括号中提取值
- c# - 使用 Windows 10 Geolocation API 时如何获得方位
- c++ - 无论我使用什么,我的输入都会被跳过
- c# - 可以在 UWP 上通过鼠标单击或滚轮滚动 CollectionView