1.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping > <class name="mypack.Monkey" table="MONKEYS"> <id name="id" type="long" column="ID">
<generator class="increment"/>
</id> <property name="name" type="string" column="NAME" /> <!--
<many-to-one
name="team"
column="TEAM_ID"
class="mypack.Team"
lazy="false"
/>
--> <!-- mapping with cascade -->
<!---->
<many-to-one
name="team"
column="TEAM_ID"
class="mypack.Team"
cascade="save-update"
lazy="false"
/> </class> </hibernate-mapping>
2.
package mypack;
public class Monkey{
private long id;
private String name;
private Team team; public Monkey() {}
public Monkey(String name, Team team) {
this.name = name;
this.team = team;
} public long getId() {
return this.id;
} public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
}
public Team getTeam() {
return this.team;
} public void setTeam(Team team) {
this.team = team;
} }
3.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping > <class name="mypack.Team" table="TEAMS" >
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id> <property name="name" type="string" column="NAME" /> </class> </hibernate-mapping>
4.
package mypack;
public class Team {
private long id;
private String name; public Team() {
} public Team(String name) {
this.name = name;
} public long getId() {
return this.id;
} public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
} }
5.
package mypack; import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.util.*; public class BusinessService{
public static SessionFactory sessionFactory;
static{
try{
// Create a configuration based on the properties file we've put
Configuration config = new Configuration();
config.configure();
sessionFactory = config.buildSessionFactory();
}catch(RuntimeException e){e.printStackTrace();throw e;}
} public List findMonkeysByTeam(Team team){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); List monkeys=session.createQuery("from Monkey as m where m.team.id="+team.getId())
.list();
tx.commit();
return monkeys;
}catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
} public Team findTeam(long team_id){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Team team=(Team)session.get(Team.class,new Long(team_id));
tx.commit();
return team;
}catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
} public void saveTeamAndMonkeyWithCascade(){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); Team team=new Team("BULL");
Monkey monkey1=new Monkey("Tom",team);
Monkey monkey2=new Monkey("Mike",team); session.save(monkey1);
session.save(monkey2); tx.commit(); }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
} public void saveTeamAndMonkey(){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); Team team=new Team("DREAM");
session.save(team); Monkey monkey1=new Monkey("Jack",team);
Monkey monkey2=new Monkey("Bill",team);
session.save(monkey1);
session.save(monkey2);
tx.commit(); }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
} public void printMonkeys(List monkeys){
for (Iterator it = monkeys.iterator(); it.hasNext();) {
Monkey monkey=(Monkey)it.next();
System.out.println("Monkeys in "+monkey.getTeam().getName()+ " :"+monkey.getName());
}
} public void test(){
saveTeamAndMonkey();
saveTeamAndMonkeyWithCascade();
Team team=findTeam(1);
List monkeys=findMonkeysByTeam(team);
printMonkeys(monkeys);
} public static void main(String args[]){
new BusinessService().test();
sessionFactory.close();
}
}
6.
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/sampledb
</property>
<property name="connection.username">
root
</property>
<property name="connection.password">
1234
</property>
<property name="show_sql">true</property>
<mapping resource="mypack/Team.hbm.xml" />
<mapping resource="mypack/Monkey.hbm.xml" />
</session-factory>
</hibernate-configuration>
7.
drop database if exists SAMPLEDB;
create database SAMPLEDB;
use SAMPLEDB; create table TEAMS (
ID bigint not null,
NAME varchar(15),
primary key (ID)); create table MONKEYS (
ID bigint not null,
NAME varchar(15),
TEAM_ID bigint,
primary key (ID)); alter table MONKEYS add index IDX_TEAM(TEAM_ID),
add constraint FK_TEAM foreign key (TEAM_ID) references TEAMS (ID);
8.
<?xml version="1.0"?>
<project name="Learning Hibernate" default="prepare" basedir="."> <!-- Set up properties containing important project directories -->
<property name="source.root" value="5.1/src"/>
<property name="class.root" value="5.1/classes"/>
<property name="lib.dir" value="lib"/>
<property name="schema.dir" value="5.1/schema"/> <!-- Set up the class path for compilation and execution -->
<path id="project.class.path">
<!-- Include our own classes, of course -->
<pathelement location="${class.root}" />
<!-- Include jars in the project library directory -->
<fileset dir="${lib.dir}">
<include name="*.jar"/>
</fileset>
</path> <!-- Create our runtime subdirectories and copy resources into them -->
<target name="prepare" description="Sets up build structures">
<delete dir="${class.root}"/>
<mkdir dir="${class.root}"/> <!-- Copy our property files and O/R mappings for use at runtime -->
<copy todir="${class.root}" >
<fileset dir="${source.root}" >
<include name="**/*.properties"/>
<include name="**/*.hbm.xml"/>
<include name="**/*.cfg.xml"/>
</fileset>
</copy>
</target> <!-- Compile the java source of the project -->
<target name="compile" depends="prepare"
description="Compiles all Java classes">
<javac srcdir="${source.root}"
destdir="${class.root}"
debug="on"
optimize="off"
deprecation="on">
<classpath refid="project.class.path"/>
</javac>
</target> <target name="run" description="Run a Hibernate sample"
depends="compile">
<java classname="mypack.BusinessService" fork="true">
<classpath refid="project.class.path"/>
</java>
</target> </project>
9.TransientObjectException