Skip to main content

Hibernate Annotation Example with Java Collection Mapping


Hi Guys,

Many a times we have data required to be mapped in the collection framework. Like suppose if we talk about a simple example of student table where a student is having having fields such as

students(sid, same, dateofbirth, qualification).

Now if we want to have some more information to be stored about student such as the number of courses he/she has enrolled, the marks obtained in the different subjects, the reference email IDs so on and so forth, then, these information can't be stored in the single table and corresponding single fields can't also be able to handle all these information.

Given the complexity of the situation we are going to separate these information in different tables such as courses, emails, marks, phones and references.

The schema of all these tables would probably be as follows:

students(sid, sname, dob, qualification);
courses(sid, cname, idx);
emails(sid, emailid, idx);
marks(sid, marks);
phones(sid, phoneno);
refs(sid, rname, rphone);

Let's assume that the students table is the primary table and corresponding tables courses, emails, marks, phones, refs are the reference tables.

I am going to achieve this in a simple java class, which later can be used in our web application for achieving the same.

For this, I am going to use following:

  • MySQL database
  • Hibernate Framework (for database operations)
  • Eclipse, for creating Java application.


First of all, create the above given tables in the mysql database as follows:

students(sid, sname, dob, qualification)
create table students(
sid int primary key auto_increment,
sname varchar(20),
dob date,
quali varchar(10));

courses(sid, cname, idx);
create table courses ( sid int, cname varchar(20), idx int);

emails(sid, emailid, idx);
create table emails ( sid int, emailid varchar(20), idx int);

marks(sid, marks);
create table marks ( sid int, marks int, idx int);

phones(sid, phoneno);
create table phones ( sid int, phone long);

refs(sid, rname, rphone);
create table refs ( sid int, rname varchar(20), rphone long);

This completes our database part.

Now, we will create our Java application

Create a Java Application in eclipse and configure your build path with Hibernate jars.
Put the following jars in the java build path

























Now, lets create a hibernate configuration xml document.

myhibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/mydb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">mypass</property>

    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
    
    <mapping class="com.rohan.hibernate.Student"/>
    </session-factory>

</hibernate-configuration>

As, we can see above property name "hbm2ddl.auto" is set as "update", which will update all the corresponding tables. Also, our mapping class is Student.java which is in the com.rohan.hibernate package.

Now, our Hibernate Util class is as follows:

AHibernateUtil.java

package com.rohan.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class AHibernateUtil {
static SessionFactory factory;

static {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg = (AnnotationConfiguration) cfg.configure("myhibernate.cfg.xml");
factory = cfg.buildSessionFactory();
}

public static SessionFactory getFactory() {
return factory;
}
}


Now we will create a package called "com.rohan.hibernate" and will put all our class here.

Now our persistent class called "Student.java"

Student.java

package com.rohan.hibernate;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Table;

import org.hibernate.annotations.CollectionOfElements;
import org.hibernate.annotations.IndexColumn;

@Entity
@Table(name="student")
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="sid")
private int sid;

@Column(name="sname")
private String sname;

@Column(name="dob")
private String dob;

@Column(name="quali")
private String qualification;

@CollectionOfElements
@JoinTable(name="courses", joinColumns=@JoinColumn(name="sid"))
@IndexColumn(name="idx")
@Column(name="cname")
private String []courses;

@CollectionOfElements
@JoinTable(name="emails", joinColumns=@JoinColumn(name="sid"))
@IndexColumn(name="idx")
@Column(name="emailid")
private List<String> emails;

@CollectionOfElements
@JoinTable(name="marks", joinColumns=@JoinColumn(name="sid"))
@IndexColumn(name="idx")
@Column(name="marks")
private List<Integer> marks;

@CollectionOfElements
@JoinTable(name="phones", joinColumns=@JoinColumn(name="sid"))
@Column(name="phoneno")
private Set<Long> phones;


@CollectionOfElements
@JoinTable(name="refs", joinColumns=@JoinColumn(name="sid"))
@Column(name="rphone")
private Map<String, Long> refs;

public Student() {}
public Student(String sname, String dob, String qualification,
String[] courses, List<String> emails, List<Integer> marks,
Set<Long> phones, Map<String, Long> refs) {
this.sname = sname;
this.dob = dob;
this.qualification = qualification;
this.courses = courses;
this.emails = emails;
this.marks = marks;
this.phones = phones;
this.refs = refs;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public String[] getCourses() {
return courses;
}
public void setCourses(String[] courses) {
this.courses = courses;
}
public List<String> getEmails() {
return emails;
}
public void setEmails(List<String> emails) {
this.emails = emails;
}
public List<Integer> getMarks() {
return marks;
}
public void setMarks(List<Integer> marks) {
this.marks = marks;
}
public Set<Long> getPhones() {
return phones;
}
public void setPhones(Set<Long> phones) {
this.phones = phones;
}
public Map<String, Long> getRefs() {
return refs;
}
public void setRefs(Map<String, Long> refs) {
this.refs = refs;
}
}


Now, we will create a java class to store the values in the students and its corresponding table.

SaveClient.java

package com.rohan.hibernate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class SaveClient {
public static void main(String[] args) {
try {
SessionFactory sf = AHibernateUtil.getFactory();
Session session = sf.openSession();
Transaction tx = (Transaction) session.beginTransaction();
String []cous = {"PHP","JDBC","JSp"};
List<String> ems = new ArrayList<String>();
ems.add("za@gmail.com");
ems.add("zb@gmail.com");
ems.add("zc@gmail.com");
List<Integer> marks = new ArrayList<Integer>();
marks.add(new Integer(70));
marks.add(new Integer(93));
marks.add(new Integer(890));
Set<Long> phs = new HashSet<Long>();
phs.add(new Long(1671));
phs.add(new Long(2267));
phs.add(new Long(3673));
Map<String, Long> refs = new HashMap<String, Long>();
refs.put("aaa", new Long(1266));
refs.put("bbb", new Long(1255));
refs.put("ccc", new Long(127));
Student stu = new Student("Anand", "21-05-12", "B.Com", cous, ems, marks, phs, refs);
session.save(stu);
tx.commit();
session.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}


Now, run the above java class to store the values in the database.
If you see the console, it will show something like this 



















Now, to retrieve the above stored values from database, we are going to write another class called 

GetDataClient.java

package com.rohan.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class GetDataClient {
public static void main(String[] args) {
try {
SessionFactory sf = AHibernateUtil.getFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Student stu = (Student)session.load(Student.class, 5);   //sid=5
System.out.println(stu.getSid()+"\t"+stu.getSname()+"\t"+stu.getDob());
for(String cn : stu.getCourses()) {
System.out.print(cn+"\t");
}
System.out.println();
System.out.println(stu.getEmails());
System.out.println(stu.getMarks());
System.out.println(stu.getPhones());
System.out.println(stu.getRefs());
tx.commit();
session.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}

Now, again run the above java class to fetch a student record from all the tables, if you see the console, it will look like as follows:











Comments

Popular posts from this blog

Struts2 and Hibernate Example using Annotation

Hi Guys, Today we are going to create an example using Struts2 and Hibernate using Annotation. For the database, we are going to use MySQL. This example will register a record for a user in the mysql database, which later will be used to login to the application. First of all we need to create our database table in MySQL. Log into your mysql database and type the following command to create a database in the mysql prompt. create database mydb; Use the above created database to create table. use mydb; Now we need to create a database table named "users". create table users( uid int primary key auto_increment, uname char(15), password char(20), email char(20), phone long, city char(15)); Now to create this application, we are going to use eclipse. Open your eclipse and create a dynamic web project. Put the following jars related to Struts2 and Hibernate in the WEB-INF/lib folder Now create the following packages in the src folder for the ...

Java program to create staircase

Observe that its base and height are both equal to  , and the image is drawn using  #  symbols and spaces.  The last line is not preceded by any spaces. Write a program that prints a staircase of size  . Input Format A single integer,  , denoting the size of the staircase. Output Format Print a staircase of size   using  #  symbols and spaces. Note : The last line must have   spaces in it. package com.rohan.test; import java.util.Scanner; public class StaircaseTest {     public static void main(String[] args) {         Scanner in = new Scanner(System.in);         int n = in.nextInt();                  for(int i = 0; i< n; i++) {         for(int k = 0; k < n; k++) {         if(k < n-i-1)         System.out.p...

Java program to print the maximum hourglass value of the matrix

Context   Given a    2D Array ,  : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in   to be a subset of values with indices falling in this pattern in  's graphical representation: a b c d e f g There are   hourglasses in  , and an  hourglass sum  is the sum of an hourglass' values. Task   Calculate the hourglass sum for every hourglass in  , then print the  maximum  hourglass sum. Note:  If you have already solved the Java domain's  Java 2D Array  challenge, you may wish to skip this challenge. Input Format There are   lines of input, where each line contains   space-separated integers describing  2D Array   ; every value in   will be in the inclusive range of   to  . Constraints Output Format Print the largest (maximum) hourglass sum f...