简体   繁体   中英

Hibernate complex data retrieval?

I have nine related tables in my database.i have to retrieve records after filtering user request.

My Entities follows ,

Movie

@Entity
@Table(name = "movie")
public class Movie implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "movie_id")
    private int movieId;

    @Column(name = "category_id")
    private Integer categoryId;

    @Column(name = "movie_title")
    private String movieTitle;

    @Column(name = "movie_description", columnDefinition = "TEXT")
    private String movieDescription;

    @Column(name = "movie_summary", columnDefinition = "TEXT")
    private String movieSummary;

    private Integer status;

    @Column(name = "language_id")
    private Integer languageId;

    @Column(name = "banner_image_url")
    private String bannerImageUrl;

    @Column(name = "imdb_rating")
    private Integer imdbRating;

    @Column(name = "rotten_tomatoes_rating")
    private Integer rottenTomatoesRating;

    @Column(name = "user_avg_rating")
    private Float userAvgRating;

    @Column(name = "main_genre_id")
    private Integer mainGenreId;

    @Column(name = "secondary_genre_id")
    private Integer secondaryGenreId;

    @Column(name = "created_by_user_id")
    private Integer createdByUserId;
}

Category

@Entity
@Table(name = "category")
public class FetchSubCategory implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "category_id")
    private Integer categoryId;

    @Column(name = "category_name")
    private String categoryName;
}

MovieActorMapping

@Entity
@Table(name = "movie_actor_mapping")
public class MovieActorMapping implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "mapping_id")
    private int mappingId;

    @Column(name = "movie_id")
    private Integer movieId;

    @Column(name = "actor_id")
    private Integer actorId;
}

MovieActors

@Entity
@Table(name = "movie_actors")
public class MovieActors implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "actor_id")
    private int actorId;

    @Column(name = "actor_name")
    private String actorName;
}

MovieGenre

@Entity
@Table(name = "movie_genre")
public class MovieGenre implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "genre_id")
    private int genreId;

    @Column(name = "genre_name")
    private String genreName;

    @Column(name = "created_by_user_id")
    private Integer createdByUserId;
}

MovieLanguage

@Entity
@Table(name = "movie_language")
public class MovieLanguage implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "language_id")
    private int languageId;

    @Column(name = "language_name")
    private String languageName;

    @Column(name = "created_by_user_id")
    private Integer createdByUserId;

    @Column(name = "last_updated_user_id")
    private Integer lastUpdatedUserId;
}

The user will request like below .all are optional fields ,

{
"subCategory":"New Release",
"language":"Malayalam",
"actor":"allu arjun",
"filmGenre":"'Family'"
}

According to the request i will return the movie list by checking conditions from corresponding table using subquery.

Method

public List<Movie> getFilterMovieList(FilterMovieRequest filterMovieRequest) throws SQLException, ClassNotFoundException, IOException {

        List<Movie> movies = null;
        try {
            String subCategory = filterMovieRequest.getSubCategory();
            String language = filterMovieRequest.getLanguage();
            String actor = filterMovieRequest.getActor();
            String filmGenre = filterMovieRequest.getFilmGenre();

            String contained = "where";
            String sql = "from Movie as M ";

            if (actor.length() > 1) {
                sql += contained + " movieId in(select movieId from MovieActorMapping where actorId in(select actorId from MovieActors where actorName='" + actor + "')) ";

                contained = "and";
            }

            if (subCategory.length() > 1) {

                sql += contained + " M.categoryId=(select categoryId from FetchSubCategory where categoryName='" + subCategory + "') ";
                contained = "and";
            }

            if (language.length() > 1) {

                sql += contained + " M.languageId=(select languageId from MovieLanguage where languageName='" + language + "') ";
                contained = "and";
            }

            if (filmGenre.length() > 1) {

                sql += contained + " (M.mainGenreId in(select genreId from MovieGenre where genreName in(" + filmGenre + ")) or M.secondaryGenreId in(select genreId from MovieGenre where genreName in(" + filmGenre + ")))";
                contained = "and";
            }

            if (contained.equals("and")) {
                Session session = sessionFactory.getCurrentSession();
                Query query = session.createQuery(sql);
                movies = query.list();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return movies;

    }

And it works fine.the problem is now i have to combine with the result in which theaters movies is playing and the show time also.

And my theater related tables follow,

theater_movie_mapping

在此处输入图片说明 theater_list

在此处输入图片说明

show_timings

在此处输入图片说明

you can see in column movie_id in theater_movie_mapping which related to my base table movie . using that we can fetch theater_id and show_id for fetch the theaters and show timing..note that i have a movie list early fetched after checking above conditions.How can i combine theaters from theater_list and show times from show_timings ? being an android developer it seems complex for me.Am totally stucked. Any help will be appreciated.Am using Spring restful webservice .

Now i have getting the result in following format,

[
    {
        "movieId": 8,
        "categoryId": 14,
        "movieTitle": "Kanyaka Talkies",
        "movieDescription": "CRITICS 3 out of 5 (Good) 3 out of 5 (Good) The composite emotional weather that the film sports makes it maddening and nurturing at once, rendering it an almost enigmatic feel. And it is this ethereal complexity that 'Kanyaka Talkies' inherently has, that makes the film singular. ",
        "movieSummary": "The concurrence of the three key characters in 'Kanyaka Talkies' isn't of the traditionalist kind; rather, by throwing the three of them together, the film does achieve the ostensibly improbable feat of placing the unlikeliest of players collectively on board, with their fates irrevocably intertwined with each other. ",
        "status": 1,
        "languageId": 1,
        "bannerImageUrl": "0",
        "imdbRating": 1,
        "rottenTomatoesRating": 3,
        "userAvgRating": 2,
        "mainGenreId": 1,
        "secondaryGenreId": 2,
        "createdByUserId": 16
    },
    {
        "movieId": 9,
        "categoryId": 14,
        "movieTitle": "Wonderful Journey",
        "movieDescription": "Wonderful Journey' is one of the most misdirecting titles as yet for a film this year. Anything but wonderful, this is an absolute cinematic misadventure that will have you pulling out your hair strands in no time. ",
        "movieSummary": "Some things in life simply cannot be averted, they say. I do agree, what with the late night show of 'Wonderful Journey' getting cancelled yesterday night and me courageously venturing out for it yet again today noon, only to embark on one of the most horrendous journeys I have ever gone for in my entire life. ",
        "status": 1,
        "languageId": 1,
        "bannerImageUrl": "0",
        "imdbRating": 1,
        "rottenTomatoesRating": 3,
        "userAvgRating": 2,
        "mainGenreId": 1,
        "secondaryGenreId": 1,
        "createdByUserId": 16
    },
    {
        "movieId": 10,
        "categoryId": 14,
        "movieTitle": "Oru New Generation Pani",
        "movieDescription": "Very occasionally does a movie come along that almost makes you vow to stay off the screens for a few weeks, and this year, the one has finally arrived. I'd gladly go ahead with a no-star rating for this one, had it not been for a technical glitch that prevents me from doing so! ",
        "movieSummary": "'Oru New Generation Pani' is an atrocity that shocks you with its attempt to spin out a story line that will have you banging you head against the rails. Inauthentic to the core, the film tells a story that will have an insomniac snoring away in no time. ",
        "status": 1,
        "languageId": 1,
        "bannerImageUrl": "0",
        "imdbRating": 1,
        "rottenTomatoesRating": 3,
        "userAvgRating": 2,
        "mainGenreId": 1,
        "secondaryGenreId": 2,
        "createdByUserId": 16
    }
]

I have to add the theaters and show time too in every json object ie ,every movie..

Assume theater_movie_mapping is mapped to Class TheaterMovie which contains Movie movie in it

ArrayList<TheaterMovie> list = new ArrayList<TheaterMovie>();
for(int i = 0 ; i < movies.size() ; i++){
list.addAll((ArrayList<TheaterMovie>)createQuery("From TheaterMovie tm where tm.movies = :mo").setParameter("mo",movies.get(i)).getList());
}

Now assume show_timings is mapped to Class ShowTiming which contains Theater theater in it

ArrayList<ShowTiming> showTimeList = new ArrayList<ShowTiming>();
for(int i = 0 ; i < list.size() ; i++){
showTimeList = (ArrayList<ShowTiming>)createQuery("From ShowTiming st where st.theater = :th").setParameter("th",list.get(i).getTheater()).getList();
}

I hope this works well for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM