首页 > 解决方案 > 如何将两个表记录映射到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;
}

我目前正在获取所有作者记录并首先创建作者对象,然后通过迭代之前创建的作者对象来查询博客,并创建博客对象将其映射到作者。有没有有效的方法来做到这一点?

SQL 小提琴链接

我无法调整图像大小,因此占据了大部分空间。

标签: javasqlpostgresqljdbc

解决方案


这是一个可能对设计代码有用的指南。

  1. 在数据库级别
    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

sql

  1. 在 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在大多数情况下也是如此


推荐阅读