Hibernate basics

NOTE : This is beginner level blog.

Sometimes We just forget the basic things if we get out of touch for some time. Hence I am writing down the basics to remind myself.

1.) One to Many mapping:
example : One User has many tasks
Screen Shot 2014-01-29 at 10.39.19 AM

@Table(name = "user")
public class User {

        private Long id;
        private List<Task> tasks

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
        public List<Task> getTasks() {
                return tasks;

        public void setTasks(List<Task> tasks) {
                this.tasks = tasks;

Here, We need to tell hibernate which is the attribute in the referencing Java Class ( In this case, Task)
which can be used to map this class with referencing class. So, in class Task, “user” is the name of attribute which is representing relationship with User Table.
We do not have any field in User table, this mapping is for hibernate, so we do not have to write a query and apply join to find all the tasks of a user.
We can access all the tasks of a user by:


2.) Many to One Mappings:
Similarly, for Task ( Multiple tasks for one user)

@Table(name = "task")
public class Task {
        private Long id;
        private String name;
        private User createdBy;

  @ManyToOne(fetch = FetchType.LAZY)
        public User getCreatedBy() {
                return createdBy;

Here, We need to join the column “createdBy” in table Task with primary key (id) of User table.
By default, it picks up the primary key of the referenced table. Also, note that I have put fetch type as lazy.

3.) One to One Mappings:
These mappings are generally useful when using composition, for example, a Task can have a Type, called as TaskType. Every task has one type, so in order to enable hibernate to fetch task type details from task without writing any query, we need to define mapping.
So, for Task Table :

@Table(name = "task")
public class Task {

    private Long id;
    private String name;
    private TaskType taskType;
    public TaskType getTaskType() {
        return taskType;

There is no need to do define any mapping in TaskType class.

These are very basic, but helpful for a quick reference.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.