Reputation: 4371
I got two classes: Forum
and Topic
.
I previously told I should have Forum attribute (in Topic), something like that:
@ManyToOne
@JoinColumn(name = "forum")
protected Forum forum;
instead of just keeping the id of the forum.
I saw that in postgresql the Forum attribute saved as "bigint" (the forum id)
so what's the point of holding the Forum reference anyway?
Upvotes: 0
Views: 2797
Reputation: 873
This is exactly why you use a object relational mapping (ORM) solution (here JPA). The problem is: you can't really put references into your database, but in your code, it's so much better to have references than plain ids. JPA does this for you. You can create a topic, set it's forum attribute, to a forum object and JPA takes care of the insertion to the database (you don't have to get the id attribute of the forum, then insert it by hand with an sql statement).
Consider this:
Forum f1 = new Forum();
Topic t1 = new Topic();
t1.forum = f1;
t1.forum.someMethod();
Simply you can navigate backwards from topic to the forum, and call the forum's method. This reference is better than having an id there:
t1.forumId = f1.id;
//to navigate back without having f1 in your scope:
Forum f2 = entityManager.find(Forum.class, t1.forumId);
f2.someMethod();
Here you had to find the forum associated with the topic as you only had an id. Much worse.
Simply put: you can easily navigate backwards (from topic to forum) in your java code, so you have a reference in your Topic class, but this can only be represented in sql as a foreign key.
ps: to be more precise JPA is an interface, the implementation used by you (eg. Hibernate, EclipseLink) is the ORM solution which does the work.
Upvotes: 1
Reputation: 359956
what's the point of holding the Forum reference anyway?
So that you can treat the forum
field in a more "object-oriented" manner, as a true field of the class, and not be concerned with the database's representation of the object graph. This is one of the big wins of using an ORM like JPA/Hibernate.
Upvotes: 2