Saturday, August 27, 2011

Hibernate Annotations with Collections (List)

Following class illustrates how to model a java.util.List in hibernate with annotations. The subjects that a student takes are given in a list. So the 'Student' class is having an instance of List of String's. This can only be used to model collections of Java built-in types.
 
package com.shyarmal.hibernate;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;

@Entity
public class Student {

    private Long id;
    private String college;
    private List<String> subjects;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }
   
    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "college")
    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }
   
    @ElementCollection(fetch = FetchType.LAZY)
    @JoinTable(name = "student_subjects",
       joinColumns = {@JoinColumn(name = "student_id")})
    public List<String> getSubjects() {
        return subjects;
    }

    public void setSubjects(List<String> subjects) {
        this.subjects = subjects;
    }
}


Annotations used to handle the scenario;
  • @ElementCollection:- Informs that the instance annotated should be considered as a Java collection type. The optional attribute 'fetch' may be given to stress how the collection should be loaded [either lazy (the default) or eager]
  • @JoinTable:- Used to explicitly specify the properties of the table which joins the collection data with the entity in concern. Name of the joining column also can be given, which links to the primary key of the entity. Inverse joining column attribute should not be specified in this case.

thanks,
Shyarmal.

2 comments:

  1. Hi Dhanuka,

    We have seen your blog. We have created a Java Forum(javainterview.co.in) and we are looking for some one who can write some good article and can work as admin for the forum.
    Will you be interested if yes please let us know.

    Thanks

    ReplyDelete
  2. Hi Gautam,

    I'm afraid I have time to administer a forum due to the busy schedule I'm adhered to. So I would have to decline your request, but I'll use your forum. Your request is appreciated.

    thanks.

    ReplyDelete