Hi all,
I'm fairly new to Hibernate and I've been trying to figure out this problem with mapping normalized table data. I've looked through the FAQs, <join>, a few tutorials, and several chapters in _Java Persistence with Hibernate_ book but was only able to find partial solutions at best.
Let's say I have two database tables in a simple message forum app:
Code:
posts(id, user_id, title, body)
users(id, username)
My domain class Post is basically:
Code:
public class Post {
private Long id;
private String username;
private String title;
private String body;
// getters/setters...
}
Essentially, I want Hibernate to map posts.user_id to users.username for my Post objects.
I know I can use the formula attribute of <property> to perform sub-select like so:
Code:
<class name=”package.Post” table=”posts”>
<!-- ... properties... -->
<property name=”username” type=”string” formula=”(select users.username from users where users.id = user_id)” />
</class>
This is fine if all I wanted to do read from the database. I would not, however, be able to change the value of username for my Post object (-- not that I would want to in a real application but this is just an example of selecting/inserting/updating normalized rows).
I tried using <join> but what ends up happening is that a new row in the table users where users.id is the same as the posts.id.
I know that Hibernate prefers one-class-per-table and I can replace String username in my Post class with a domain object User but I rather stick with a simple String mapping.
Is this possible to do this type of normalized/denormalized mapping Hibernate without resorting to custom SQL inserts/updates?
Thanks,
Jim