HIBERNATE - Persisting Collections
Posted On July 4, 2007 by Ramdas S filed under Java
In this brief tutorial, we will see a practical and simple example for persisting a collection like an ArrayList using Hibernate and MySql. Kindly read this tutorial as a sequel to the earlier tutorials on Hibernate (DeveloperIQ Aug and Sep 2005 issues).
In our example, there are two classes — team.java and member.java.
As already seen, we begin any hibernate example with some essential files in our classpath.
a) hibernate.properties;
b) Mapping document(s); and
c) Class files of objects being persisted.
As we are having two classes here, we will have two source files and corresponding mapping documents.
In the first tutorial, (Aug) we had used 'hilo' generator. In the second tutorial, we switched over to 'increment' generator. This time, we are using 'native' generator. As you may recall, the generator is a mechanism for automatic creation of 'id'. Each database product follows its own scheme.
We are now in c:\hiberdemo\list\team. We have created the following files in this folder:
a) hibernate.properties;
b) team.java;
c) member.java;
d) team.hbm.xml;
e) member.hbm.xml;
f) log4j.properties;
g) setpath.bat;
h) setcpath.bat; and
i) hiberdemo1.java.
The hibernate.properties file is the same as that in previous tutorials, because, it describes the database details being used and as we are using the same MySql database here also, there will be no changes.
hibernate.dialect=
net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=
com.mysql.jdbc.Driver
hibernate.connection.url=
jdbc:mysql://localhost/hiberdemo
hibernate.connection.username
hibernate.connection.password
-----------
We then create two java class files, which are just attribute beans. Refer code 1.
--------------------------------------
import java.util.*;
public class team
{
String name;
List members;
int id;
public team() { }
public team(String d)
{ name=d; }
public String getName()
{ return name; }
public void setName(String a) { name = a; }
public List getMembers()
{ return members; }
public void setMembers(List b) { members = b; }
public int getId()
{ return id; }
public void setId(int s)
{ id = s; }
}
-------------------------------------
import java.util.*;
public class member
{
String info;
int id;
public member() { }
public member(String d)
{ info=d; }
public String getInfo()
{ return info; }
public void setInfo(String a)
{ info = a; }
public int getId()
{ return id; }
public void setId(int s)
{ id = s; }
}
---
As before, we create the mapping documents as given in code 2.
// member.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="member"
table="member">
<id name="id" unsaved-value="0">
<generator class="native"/>
</id>
<property name="info" />
</class>
</hibernate-mapping>
======================================
// team.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="team" table="team">
<id name="id" unsaved-value="0">
<generator class="native"/>
</id>
<list name="members" cascade="all">
<key column="parent_id" />
<index column="idx" />
<one-to-many class="member" />
</list>
<property name="name"
type="string" />
</class>
</hibernate-mapping>
=
The setpath.bat file follows:
set path=c:\windows\command;d:\jdk1.4.2\bin
The setcpath.bat follows:
set classpath=c:\hiberdemo\list\team;
c:\hibernate2\lib\cglib-full-2.0.2.jar;
c:\hibernate2\lib\commons-collections-2.1.1.jar;
c:\hibernate2\lib\commons-logging-1.0.4.jar;
c:\hibernate2\lib\dom4j-1.4.jar;
c:\hibernate2\lib\ehcache-0.9.jar;
c:\hibernate2\lib\jdbc2_0-stdext.jar;
c:\hibernate2\lib\jta.jar;
c:\hibernate2\lib\log4j-1.2.8.jar;
c:\hibernate2\lib\xerces-2.4.0.jar;
c:\hibernate2\lib\xml-apis.jar;
c:\hibernate2\hibernate2.jar;
c:\hibernate2\lib\commons-pool-1.2.jar;
c:\hibernate2\lib\commons-dpcp-1.2.1.jar;
c:\hibernate2\lib\mysqljava3.jar;
c:\hibernate2\lib\jgroups-2.2.3.jar;
c:\hibernate2\lib\odmg-3.0.jar
----------------------------------
As the correct procedure for locating these jar files has already been given in the earlier tutorials, readers are requested to refer to them.
--
We now create the client-console program to add records (code 3).
// hiberdemo1.java
import java.io.*;
import java.util.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
class hiberdemo1
{
public static void main(String args[])
{
SessionFactory factory = null;
System.out.println("starting!");
try
{
Configuration cfg =
new Configuration();
cfg.addClass(team.class);
cfg.addClass(member.class);
factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
tx = session.beginTransaction();
team team1 = new team("Hockey");
ArrayList list1 = new ArrayList();
list1.add(new member("john"));
list1.add(new member("sam"));
list1.add(new member("tom"));
team1.setMembers(list1);
session.save(team1);
tx.commit();
session.flush();
//----------------------------------
team team2 = new team("Cricket");
ArrayList list2 = new ArrayList();
list2.add(new member("martin"));
list2.add(new member("das"));
list2.add(new member("antony"));
team2.setMembers(list2);
session.save(team2);
tx.commit();
session.flush();
session.close();
}catch(Exception e1)
{ System.out.println(""+e1); }
} // MAIN
}
========================================
If you have followed the earlier tutorial, the code is self-explanatory and lucid.
It is assumed that we have already started the MySql database and created the two tables with the schema as given below:
1) create table team (id int not null primary key auto_increment, name text);
2) create table member(id int not null primary key auto_increment,
info text,idx int,parent_id int);
---------------------------------
Now, we can compile and run the console program. The code has been tested and found to work correctly.
***********************************
