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);
create table marks ( sid int, marks int, idx int);
create table phones ( sid int, phone long);
create table refs ( sid int, rname varchar(20), rphone long);
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
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
Post a Comment