JPA OneToOne relationships returning null The 2019 Stack Overflow Developer Survey Results Are InAvoiding != null statementsJPA EntityManager: Why use persist() over merge()?Wrong ordering in generated table in jpaIs null check needed before calling instanceof?Create the perfect JPA entityJPA/Hibernate - inverse join on unidirectional OneToOne association?What's the difference between JPA and Hibernate?What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany associationJPA: Querying a OneToOne relationship with an abstract classHibernate : Why FetchType.LAZY-annotated collection property eagerly loading?

Cooking pasta in a water boiler

Will it cause any balance problems to have PCs level up and gain the benefits of a long rest mid-fight?

Why isn't the circumferential light around the M87 black hole's event horizon symmetric?

Why doesn't UInt have a toDouble()?

What is this sharp, curved notch on my knife for?

Kerning for subscripts of sigma?

Geography at the pixel level

The phrase "to the numbers born"?

Can we generate random numbers using irrational numbers like π and e?

Match Roman Numerals

Deal with toxic manager when you can't quit

Are there any other methods to apply to solving simultaneous equations?

How do you keep chess fun when your opponent constantly beats you?

Is it ok to offer lower paid work as a trial period before negotiating for a full-time job?

Pokemon Turn Based battle (Python)

Output the Arecibo Message

Is Cinnamon a desktop environment or a window manager? (Or both?)

Getting crown tickets for Statue of Liberty

What can I do if neighbor is blocking my solar panels intentionally

Short story: man watches girlfriend's spaceship entering a 'black hole' (?) forever

Does adding complexity mean a more secure cipher?

What force causes entropy to increase?

What to do when moving next to a bird sanctuary with a loosely-domesticated cat?

What could be the right powersource for 15 seconds lifespan disposable giant chainsaw?



JPA OneToOne relationships returning null



The 2019 Stack Overflow Developer Survey Results Are InAvoiding != null statementsJPA EntityManager: Why use persist() over merge()?Wrong ordering in generated table in jpaIs null check needed before calling instanceof?Create the perfect JPA entityJPA/Hibernate - inverse join on unidirectional OneToOne association?What's the difference between JPA and Hibernate?What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany associationJPA: Querying a OneToOne relationship with an abstract classHibernate : Why FetchType.LAZY-annotated collection property eagerly loading?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have this class



public class Hotel implements Serializable 


@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "FILE_ID")
private File file;

..



and this query



Query query = em.createQuery("SELECT file.hotel FROM File file where file.id = :id ");


and I would like to know if it is possible to return an empty Hotel object instead of null if the hotel does not exists in the relationship but the file exists










share|improve this question



















  • 1





    I think you query should be more like SELECT hotel.file from .... And no, you can't return an empty hotel as that would still have to be in the database. The only thing you can do is use @PostLoad and check if the result is null and if so, set it to an empty hotel

    – XtremeBaumer
    Mar 8 at 11:18


















0















I have this class



public class Hotel implements Serializable 


@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "FILE_ID")
private File file;

..



and this query



Query query = em.createQuery("SELECT file.hotel FROM File file where file.id = :id ");


and I would like to know if it is possible to return an empty Hotel object instead of null if the hotel does not exists in the relationship but the file exists










share|improve this question



















  • 1





    I think you query should be more like SELECT hotel.file from .... And no, you can't return an empty hotel as that would still have to be in the database. The only thing you can do is use @PostLoad and check if the result is null and if so, set it to an empty hotel

    – XtremeBaumer
    Mar 8 at 11:18














0












0








0


1






I have this class



public class Hotel implements Serializable 


@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "FILE_ID")
private File file;

..



and this query



Query query = em.createQuery("SELECT file.hotel FROM File file where file.id = :id ");


and I would like to know if it is possible to return an empty Hotel object instead of null if the hotel does not exists in the relationship but the file exists










share|improve this question
















I have this class



public class Hotel implements Serializable 


@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "FILE_ID")
private File file;

..



and this query



Query query = em.createQuery("SELECT file.hotel FROM File file where file.id = :id ");


and I would like to know if it is possible to return an empty Hotel object instead of null if the hotel does not exists in the relationship but the file exists







java spring hibernate jpa hibernate-mapping






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 11:45







carles xuriguera

















asked Mar 8 at 11:11









carles xurigueracarles xuriguera

30713




30713







  • 1





    I think you query should be more like SELECT hotel.file from .... And no, you can't return an empty hotel as that would still have to be in the database. The only thing you can do is use @PostLoad and check if the result is null and if so, set it to an empty hotel

    – XtremeBaumer
    Mar 8 at 11:18













  • 1





    I think you query should be more like SELECT hotel.file from .... And no, you can't return an empty hotel as that would still have to be in the database. The only thing you can do is use @PostLoad and check if the result is null and if so, set it to an empty hotel

    – XtremeBaumer
    Mar 8 at 11:18








1




1





I think you query should be more like SELECT hotel.file from .... And no, you can't return an empty hotel as that would still have to be in the database. The only thing you can do is use @PostLoad and check if the result is null and if so, set it to an empty hotel

– XtremeBaumer
Mar 8 at 11:18






I think you query should be more like SELECT hotel.file from .... And no, you can't return an empty hotel as that would still have to be in the database. The only thing you can do is use @PostLoad and check if the result is null and if so, set it to an empty hotel

– XtremeBaumer
Mar 8 at 11:18













1 Answer
1






active

oldest

votes


















0














Since you're using JPA, you could make use of a repository. JPA can automatically return a type of Optional<>. Via Optional.isPresent() you can check if the query returned something.



A repository could look like this:



public interface FileRepository extends JpaRepository<File, Long> 
Optional<File> findById(Long id);







share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55062001%2fjpa-onetoone-relationships-returning-null%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Since you're using JPA, you could make use of a repository. JPA can automatically return a type of Optional<>. Via Optional.isPresent() you can check if the query returned something.



    A repository could look like this:



    public interface FileRepository extends JpaRepository<File, Long> 
    Optional<File> findById(Long id);







    share|improve this answer



























      0














      Since you're using JPA, you could make use of a repository. JPA can automatically return a type of Optional<>. Via Optional.isPresent() you can check if the query returned something.



      A repository could look like this:



      public interface FileRepository extends JpaRepository<File, Long> 
      Optional<File> findById(Long id);







      share|improve this answer

























        0












        0








        0







        Since you're using JPA, you could make use of a repository. JPA can automatically return a type of Optional<>. Via Optional.isPresent() you can check if the query returned something.



        A repository could look like this:



        public interface FileRepository extends JpaRepository<File, Long> 
        Optional<File> findById(Long id);







        share|improve this answer













        Since you're using JPA, you could make use of a repository. JPA can automatically return a type of Optional<>. Via Optional.isPresent() you can check if the query returned something.



        A repository could look like this:



        public interface FileRepository extends JpaRepository<File, Long> 
        Optional<File> findById(Long id);








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 12:43









        Sige VVSige VV

        317




        317





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55062001%2fjpa-onetoone-relationships-returning-null%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            1928 у кіно

            Захаров Федір Захарович

            Ель Греко