Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Java Hibernate Cookbook

You're reading from  Java Hibernate Cookbook

Product type Book
Published in Sep 2015
Publisher
ISBN-13 9781784391904
Pages 250 pages
Edition 1st Edition
Languages

Table of Contents (15) Chapters

Java Hibernate Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
1. Setting Up Hibernate 2. Understanding the Fundamentals 3. Basic Annotations 4. Working with Collections 5. Working with Associations 6. Querying 7. Advanced Concepts 8. Integration with Other Frameworks Index

Providing an annotation-based hibernate mapping


When we choose the annotation-based way to provide a configuration, we don't need to create any hibernate mapping (usually *.hbm. xml) file. Hibernate provides the annotations that we can directly write to the POJO, and we can provide all the mappings via the classes, which we can do using the previous XML file.

How to do it…

Now, let's create the class that contains the annotation-based mapping. As we used the Employee class to provide XML-based mapping here, we will use the same class with annotations:

  1. Represent the annotation-based mapping for the Employee class in Employee.java, as shown in the following code:

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name="employee")
    public class Employee{
    
      @Id
      @Column(name="id")
      @GeneratedValue(strategy = GenerationType.AUTO)
      private long id;
    
      @Column(name="firstname")
      private String firstName;
    
      @Column(name = "salary")
      private double salary;
    
      // default constructor
      public Employee() {
      }
    
      public long getId() {
        return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getFirstName() {
          return firstName;
      }
    
      public void setFirstName(String firstName) {
        this.firstName = firstName;
      }
    
      public double getSalary() {
        return salary;
      }
    
      public void setSalary(double salary) {
        this.salary = salary;
      }
    
    }

How it works…

Now, compare the annotations with the XML mapping to gain a better understanding of the difference between the two methods.

Declaring a class — Table for the database

In the annotations, we will write the following code:

@Entity
@Table(name="employee")
public class Employee{...}

Now, check the XML mapping for the same here:

<class name="Employee" table="employee">

The keywords used in the preceding class are described below:

  • @Entity: This annotation declares the class as an entity bean.

  • @Table: We can set this annotation at the class level only. You can provide the name attribute, which is considered as a database table name. You can also just write @Table without any attribute; in this case, the class name is considered as a table name by hibernate.

Declaring an ID — The primary key for the table

In the annotations, we will write the following code:

@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

Now, check the XML mapping for the same in the following code:

<id name="id" type="long" column="id">
  <generator class="auto" />
</id>

The annotations used in the preceding code are described below:

  • @Id: This annotation declares the property to be an identifier property, and this is used as a primary key for the table.

  • @Column: This annotation is used to define the column for the table. Here, we used name="id", meaning that hibernate considers the column name to be "id". You can also write @Column without any attributes; in this case, the property name is considered to be a column name for the table.

  • @GeneratedValue: Using this annotation, we can provide information to hibernate on how to generate a value for the primary key column. Here, we will use strategy = GenerationType.AUTO, which means that hibernate uses the autoincrement value for the id column. If not provided, hibernate uses the most appropriate generation strategy.

Referencing an object

In the annotations, we will write the following code:

@JoinColumn(name="department")
@ManyToOne
private Department department;

Now check the XML mapping for the same in the following code:

<many-to-one name="department" class="Department">
  <column name="department"/>
</many-to-one>

The annotations used in the preceding code are described below:

  • @JoinColumn: This annotation notifies hibernate that this is a reference column.

  • @ManyToOne: This annotation defines the relation between the referenced tables. Here, we have used many-to-one, meaning that one department can be mapped with multiple employees.

There's more…

In the previous section you learned how to reference a class using hibernate. In this section, we will take a look at how to provide the reference of one class in another class in detail.

Do not get confused when writing Employee.java again to show the reference object annotation.

The following code represents the annotation-based mapping for the Employee class that has the reference field in Employee.java:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="employee")
public class Employee{

   @Id
   @Column(name="id")
   @GeneratedValue(strategy = GenerationType.AUTO)
   private long id;
   
   @Column(name="firstname")
   private String firstName;
   
   @Column(name = "salary")
   private double salary;
   
   @JoinColumn(name="department")
   @ManyToOne
   private Department department;
   
   // default constructor
   public Employee() {
   }
   
   // getters & setters
   public long getId() {
   return id;
   }
   
   public void setId(long id) {
   this.id = id;
   }
   
   public String getFirstName() {
   return firstName;
   }
   
   public void setFirstName(String firstName) {
   this.firstName = firstName;
   }
   
   public double getSalary() {
   return salary;
   }
   
   public void setSalary(double salary) {
   this.salary = salary;
   }
   
   public Department getDepartment(){
   return department;
   }

  public setDepartment(Department department){
    this.department = department;
  }
}

The following code represents the annotation-based mapping for the Department class in Department.java:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table //If name is not supplied hibernate will use class name as table name
public class Department{
  @Id
  @Column //If name is not supplied hibernate will use field name as column name
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  @Column
  private String deptName;
  
  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getDeptName() {
    return deptName;
  }

  public void setDeptName(String deptName) {
    this.deptName = deptName;
  }

}
You have been reading a chapter from
Java Hibernate Cookbook
Published in: Sep 2015 Publisher: ISBN-13: 9781784391904
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}