首页 > 解决方案 > 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 ?

标签: javaspringhierarchy

解决方案


如果我正确理解了您的问题,您实际上可以创建一个抽象Media类,并使 theVideoPhoto类都从它扩展。

要对 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


希望这可以帮助。


推荐阅读