我正在尝试将相册详细信息和与该相册相关联的所有图片设置为设置piSet
,但它并未提取所有图像来设置piSet
我想要
albumname in al object
ABC
images in piSet
image1
image2
image3
....
数据提取代码是
con = ConnectionFactory.getConnection();
List<Album> aList = new ArrayList<Album>();
try {
ps = con.prepareStatement("select distinct album.*,pi.* from "
+ "atom as a "
+ "left join album as album "
+ "on "
+ "a.id=album.aid "
+ "left join post_images as pi "
+ "on "
+ "album.id=pi.album_id "
+ "where "
+ "a.id=? "
+ "and a.status=? ");
ps.setLong(1, aid);
ps.setString(2, "Active");
rs = ps.executeQuery();
while (rs.next()) {
Set<PostImages> piSet = new HashSet<PostImages>();
Album al = new Album();
al.setId(rs.getLong("album.id"));
al.setName(rs.getString("album.name"));
PostImages pi = new PostImages();
pi.setImageId(rs.getLong("pi.image_id"));
pi.setLargePicPath(rs.getString("pi.large_pic_path"));
piSet.add(pi);
al.setPostImageses(piSet);
aList.add(al);
}
} catch (SQLException e) {}
如何修改上述代码以将所有图像提取到PiSet&#39;。
答案 0 :(得分:2)
假设 id 在 album 表中是唯一的,上面的代码可以满足您的要求:
rs = ps.executeQuery();
HashMap<Long, Album> AlbumMap = new HashMap<Long, Album>();
while (rs.next()) {
Long albumId = rs.getLong("album.id");//assume album.id is unique.
Album al = AlbumMap.get(albumId);
if (al == null) {
al = new Album();
al.setId(albumId);
al.setName(rs.getString("album.name"));
Set<PostImages> piSet = new HashSet<PostImages>();
al.setPostImageses(piSet);
aList.add(al);
AlbumMap.put(albumId, al);
}
PostImages pi = new PostImages();
pi.setImageId(rs.getLong("pi.image_id"));
pi.setLargePicPath(rs.getString("pi.large_pic_path"));
al.getPostImageses().add(pi);
}
答案 1 :(得分:0)
您需要保留从id到Album
个实例的地图,并且只有在没有针对给定ID的实例时才创建新的Album
。
我还建议您让Album
在内部处理Set
,只需将图片添加到相册,而不是将设置设置为相册。
Map<Long, Album> albumMap = new HashMapMap<>();
while (rs.next()) {
long albumId = rs.getLong("album.id");
Album album = albumMap.get(albumId);
if (albumId = null) {
album = new Album();
album.setId(albumId);
album.setName(rs.getString("album.name"));
albumMap.put(albumId, album);
)
PostImages pi = new PostImages();
pi.setImageId(rs.getLong("pi.image_id"));
pi.setLargePicPath(rs.getString("pi.large_pic_path"));
// Don't handle the set yourself, let Album handle it.
album.addPostImage(pi);
}
aList.addAll(albumMap.values());
顺便说一句:在ResultSet.getXXX
中使用表前缀不是JDBC标准,据我所知 - 是MySQL特有的;它会使你的代码在不同数据库之间的可移植性降低。