开发者

How to get hibernate to return entity even if entity doesn't exist in database

开发者 https://www.devze.com 2023-02-02 01:35 出处:网络
Ok, im not sure how to put this. But here goes. say i have a database with the tables movie and user_movie, movie holds information on any given movie, and user_movie holds information on the users r

Ok, im not sure how to put this. But here goes.

say i have a database with the tables movie and user_movie, movie holds information on any given movie, and user_movie holds information on the users relationship to the movie.

So, when a user sets the value "watched" on a given movie, then this results in a table record in user_movie. however, if a user doesn't set any movies as watched, then this would mean that the no movies have been watched and no records are set. so there is this logic already in place. (Now i could always have just created a default record for each and every user times the number of movies. but this wouldn't be very effective.)

so when i try to create a query like, fetch me all movies that the user hasn't watched. that should return me a list of ALL the movies in the database. however, since user_media doesn't contain any records, it would actually give开发者_如何学C me an empty list.

so is there a solution i could use here?

Is it possible to get hibernate to return a "default" entity in the event that the entity doesn't exist? or in the event of a "left join" and the joined value is NULL can i return a default value?

my current backend is mysql. maybe i could create a custom function to deal with this problem?

EDIT

user_media can also hold values like acquired (true,false), wishlisted (true,false), emotion (LOVE,HATE,NULL)

A requirement for my solution is that i get a list of user_media joined with movie. Therefore user_media can't be NULL.


This query in MySQL will return you the list of movies user 1 hasn't watched:

SELECT  *
FROM    movie
WHERE   id NOT IN
        (
        SELECT  movie_id
        FROM    user_movie
        WHERE   user_id = 1
                AND watched = 1
        )

Create a UNIQUE index (or, better, a PRIMARY KEY) on user_movie (user_id, movie_id) for this to work fast.

A test case:

CREATE TABLE movie (id INT NOT NULL PRIMARY KEY, name TEXT);

CREATE TABLE user_movie (user_id INT NOT NULL, movie_id INT NOT NULL, watched BOOL, PRIMARY KEY (user_id, movie_id));

INSERT
INTO    movie
VALUES
        (1, 'Titanic'),
        (2, 'Office Space'),
        (3, 'Surf Nazis Must Die');

INSERT
INTO    user_movie
VALUES  (1, 1, FALSE),
        (1, 2, TRUE);

SELECT  *
FROM    movie
WHERE   id NOT IN
        (
        SELECT  movie_id
        FROM    user_movie
        WHERE   user_id = 1
                AND watched = 1
        );

This will return

1, 'Titanic'
3, 'Surf Nazis Must Die'

Titanic is returned because the user explicitly told he didn't watch it, Surf Nazis Must Die is returned because the user didn't insert a record for it.

0

精彩评论

暂无评论...
验证码 换一张
取 消