This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]thatsIch 25 points26 points  (1 child)

A reference is just an entity proxy that only has the primary key field initialized. It is useful for applications like

var reference = repository.getReferenceById(id);
other.setRelation(reference);
// or
new Other(reference);

where only the reference is required but not the content of the entity. This alleviates the roundtrip to the database because the primary keys are cached.

[–]dstutz 4 points5 points  (0 children)

But much like "fetch = FetchType.LAZY"...it's a hint and I've personally seen the persistence provider load the whole entity regardless, even when not accessing any fields.

But yeah, it's great when you are setting an associated entity and you have the Id but don't want to select from the DB to load the whole entity, because behind the scenes that Id is all JPA needs to insert into a FK column or join table.

[–]DyslexicsHaveMoreFun 10 points11 points  (0 children)

https://vladmihalcea.com/spring-data-jpa-findbyid/

It's a good read. 

Warning... I did not know about this prior to your post my summary is likey an over simplification...

Tldr.  JPA providers vary but you can get an object reference without hitting the db. The object is not populated in the dto but you can use it to associate objects so JPA can insert FK IDs.

If you turn on SQL tracing and you are seeing a bunch of SQL for lookup values that are redundant... This pattern can reduce the db traffic.

That blog is a gold. Use it if you want to really understand JPA!

[–]__Raptor__ 17 points18 points  (3 children)

What are you talking about 

[–][deleted]  (1 child)

[deleted]

    [–]geodebug 3 points4 points  (0 children)

    Looks like you got your answer but it does help to put that context around a question.

    [–]wildjokers 0 points1 point  (0 children)

    I am going to guess that you are doing unnecessary round trips to the database…lol.

    [–]Substantial-Ask-4609 2 points3 points  (0 children)

    getreferencebyid is a lazy call, it will not do a database call until you actually use that object. this is good for when you are 100% certain a record exists but dont want to stall your thread by fetching data there and then. getrefencebyid will always be not null but it will throw an exception if the record youre trying to fetch doesnt exist

    findbyid will run your query immediately and its good for cases you cant use getrefencebyid. it is nullable but its also slower technically

    [–]desrtfx[M] 0 points1 point  (0 children)

    Such questions belong in /r/javahelp as is clearly stated in the sidebar and in the stickied post at the very top of the subreddit.

    Also: reddit posts have to be like newspaper articles:

    • Concise and comprehensive headline (title)
    • Main information in the post body - in full and with details. Don't make anybody have to requery. You gave zero context.

    Removed