java - 如何将两个表记录映射到java对象列表
问题描述
我在 postgresql 数据库中有两个表作者和博客,我想使用简单的 JDBC 客户端检索记录并映射/绑定到列表对象,下面是表和对象详细信息
架构详细信息
author (TABLE)
id VARCHAR(10)
name VARCHAR(200)
dob VARCHAR(200)
blogsv (TABLE)
id VARCHAR(10)
author VARCHAR(10)
subject VARCHAR(200)
content VARCHAR(200)
作者表
博客表
public class Author{
private String id;
private String name;
private Date dob;
private List<Blogs> blogs; // Bind related blog records
}
public class Blog{
private String id;
private String authorId;
private String subject;
private Date content;
}
我目前正在获取所有作者记录并首先创建作者对象,然后通过迭代之前创建的作者对象来查询博客,并创建博客对象将其映射到作者。有没有有效的方法来做到这一点?
我无法调整图像大小,因此占据了大部分空间。
解决方案
这是一个可能对设计代码有用的指南。
- 在数据库级别
a)blogsv
上,列author
应该是int
并且是外键author
(FK
需要标记为create-table
)
它甚至可以工作,varchar
但是用于一致设计的数据库规则被破坏
b) 最好使用一个带有连接的查询来检索一个中的所有日期片
select author.id, author.name, author.dob,
blogsv.id blogId,blogsv.subject, blogsv.content
from author left join blogsv on author.id = blogsv.author
- 在 Java 端
a)在映射上使用对应类型(sql-columns to java)
public class Author{
private int id;
private String name;
private Date dob;
//could also create by default an empty list for each author;
private List<Blogs> blogs = new ArrayList<Blogs>();
// Bind related blog records
}
public class Blog{
private int id;
//do not need since it's on top level (nested with author)
//private String authorId;
private String subject;
private Date content;
}
b) 增强逻辑
//better to use a map for easy access to author by id
Map<Integer, Author> authorMap = new HashMap<>();
//after retrieve data from sql
//loop each record
//check if author is key on Map
//NO: create new author
authorMap.put(id, new Author(...))
//YES: retrieve author
Author a = authorMap.get(id)
//add blog detail if any (fields are not null)
//need also to retrieve from java associate blogList
a.getBlogList().add(blogDetails)
//end loop
注意:在一定id
程度上被定义为varchar
罚款,但主要PK
应该是integer
,而且autoincrement
在大多数情况下也是如此
推荐阅读
- java - 我被困在Java中的第一个hackerrank挑战中
- javascript - Bootstrap 4 selectpicker基于所选值打开模式
- php - 替换功能不适用于多次替换
- html - 如何在 bootstrap 4 下拉菜单中应用网格系统来塑造它像附加的图像?
- regex - 解开交错的日志(文本)文件
- javascript - 无法在条形图中设置列的宽度
- javascript - 如何使用 JavaScript 将联系人添加到 Dynamics CRM 365
- java - 将对象从 API 资源方法传递到 APIFilter PostCheckMethod
- linux - linux中的dlltool等效
- laravel - 无法在 Heroku 上部署 Laravel 应用程序的 Docker 映像