java - How can i get a list of Media class and it returns two entities?
问题描述
I have two classes Video and Photo in a spring web application,using jpa, mysql, amazon s3, What i want is to be able to return in my view a list of Media meaning both video and photos together as one Entity. Is there a way to do this. i need an idea.
Idea
If i create a Media class and make photo and video extend this class will that in a way help? Is there a way to say getMediaList and its returns video and entity ordered by date of creation ?
解决方案
如果我正确理解了您的问题,您实际上可以创建一个抽象Media
类,并使 theVideo
和Photo
类都从它扩展。
要对 a 中的所有元素进行排序List<Media>
,您可以实现一种sort
在日期字段上使用比较器的方法。
例如,类可以按如下方式组织:
public abstract class Media {
protected Date createdOn;
protected String name;
protected Date getCreationDate() {
return createdOn;
}
public String getName() {
return name;
}
public static void sort(List<Media> movieItems) {
movieItems.sort(Comparator.comparing(Media::getCreationDate));
}
}
public class Video extends Media {
private String someAttribute;
public Video(Date date, String name) {
createdOn = date;
this.name = name;
}
}
public class Photo extends Media {
private String someOtherAttribute;
public Photo(Date date, String name) {
createdOn = date;
this.name = name;
}
}
以下代码
public class Main {
public static void main(String[] args) {
// Create first element
Date date1 = new Date(System.currentTimeMillis());
Video video1 = new Video(date1, "Timelapse");
// Create second element
Date date2 = new Date(System.currentTimeMillis() - 1000);
Photo photo1 = new Photo(date2, "My pretty picture");
// Create list
ArrayList<Media> myMedia = new ArrayList<>();
myMedia.add(video1);
myMedia.add(photo1);
// Original
System.out.println("Original list:");
printMediaList(myMedia);
// Sorted
System.out.println("Sorted list:");
Media.sort(myMedia);
printMediaList(myMedia);
}
public static void printMediaList(List<Media> myMedia) {
for (int i = 0; i < myMedia.size(); i++) {
System.out.printf("%d. %s\n", i + 1, myMedia.get(i).getName());
}
System.out.println();
}
}
输出这个
Original list:
1. Timelapse
2. My pretty picture
Sorted list:
1. My pretty picture
2. Timelapse
希望这可以帮助。
推荐阅读
- go - 如何检查函数的返回值是否满足错误接口
- database - 如何有条件地在 MongoDB 集合中的所有子文档上设置新字段
- vb.net - 如何在 vb.net 的子目录中更改全局变量的值
- html - Powershell - 如何使用 XPath 提取本地 html 文件的元素
- java - 自定义 Gradle Java 插件在 v5.2.1 中崩溃,但在 v4.7 中有效?
- scala - 等效于 sbt 的 maven 原型
- excel - INDEX/MATCH 近似匹配,无需排序
- reactjs - 向 Express 和 Mongo DB 提出请求
- r - 如何有效地计算加权比例和置信区间?
- ruby-on-rails - 计算使用活动存储显示的视频的观看次数