Say I have domain objects corresponding to Posts
and Users
. Nevertheless, I have corresponding database tables containing information relevant to "posts" and "users".
Currently I have properly set up the mapping in Hibernate so that I can pull the info from the "posts" table and save it as a Post
object. However, I then added to my Posts
domain object, a reference to a User
object (so that each post can have a corresponding User
object).
In my database structure, the "posts" table has a user_id
column which is a foreign key into the "users" table.
My question is: when querying the "posts" table in my DAO, do I have to join on the "users" table and then somehow cast the returned user data into a User
object? Or can I simply leave my query as it is (i.e. just querying the "posts" table), and somehow add a hibernate mapping so that the User
attribute in the Posts
table gets populated? (I guess I am wondering if Hibernate can automatically generate the join for me if I set up the mapping properly - examples would be great too!)
Thanks, and I hope I was clear enough.
Update: Just to clarify, here are some code snippets:
My Post Object:
public class Posts {
private String title;
...
private User user;
//getters and setters here
}
My Post table columns:
post_id (primary key)
title
...
user_id (foreign key into User table)
My mapping (without taking into account the User attribute) currently looks like this:
<class name="com...Post" table="post">
<id name="pId" column="post_id" />
<property name="title" column="title" type="java.lang.String" />
...
<!-- Need to add mapping here to join with user table?? -->
</class>
So basically, my DAO currently fetches a Post object without the private User user
attribute (since I just added this). My question was how do I populate that attribute in the Post object (so that the fetched Post object also contains a User object)?
Sorry if the current posts already answered this...they were just slightly confusing to me..