我在 postgresql DB 中有两个表作者和博客,我想使用简单的 JDBC 客户端检索记录并映射/绑定到 List 对象,下面是表和对象的详细信息
架构详情
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;
}
我目前正在获取所有作者记录并首先创建作者对象,然后通过迭代之前创建的作者对象来查询博客,并创建博客对象将其映射到作者。有没有什么有效的方法可以做到这一点?
我无法调整图像大小,因此占据了大部分空间。
答案 0 :(得分:0)
这是一个可能对设计代码有用的指南。
blogsv
,列 author
应该是 int
并且是 author
的外键
FK
上标记create-table
)
varchar
也能正常工作,但是一致性设计的 DB 规则被破坏了
select author.id, author.name, author.dob,
blogsv.id blogId,blogsv.subject, blogsv.content
from author left join blogsv on author.id = blogsv.author
a) 使用对应类型进行映射(sql-columns 到 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
答案 1 :(得分:0)
从长远来看,使用带有相应实体的 JPA 提供程序将是有益的
javax.persistence.
实体(@Entity
)@OneToMany(mappedBy = "author")
中为 Author
定义 List<Blog> blogs
@ManyToOne @JoinColumn(name="author")
中为 Blog
定义 private Author author