0% found this document useful (0 votes)
8 views29 pages

Module 4 - Association Mapping (1)

use ful for java developer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views29 pages

Module 4 - Association Mapping (1)

use ful for java developer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Association Mapping

 If you want to establish the relationship among different Entity classes, then you
have to use Association Mapping.

 When there is IS-A Relation between two Entities then follow Inheritance Mapping.
Ex:
GoldCustomer IS A Customer
SilverCustomer IS A Customer.

 When there is HAS-A Relation between two Entities then follow Association
Mapping.
Ex:
Customer HAS A Address
Customer HAS A Order

 You can Implement Association Mapping based on two factors.


o Cardinality
o Directionality
 Cardinality represents number of objects participating in Relationship on both the
Sides.
 Depending on the Cardinality, there are 3 types of Association Mapping:
o One to One Mapping
o One to Many Mapping
o Many to Many Mapping
 Directionality represents whether we can access the Data in One direction only or
both the directions.
 Depending on the Directionality, You can establish two type of relationship:
o Uni-Directional Relationship
o Bi-Directional Relationship

1) One-One Relationship

 Consider Relation between Customer and Address

First Direction: Customer => Address (Uni-Directional)


1 Customer can have 1 address => One-One Mapping

Second Direction: Address => Customer (Bi-Directional)


1 Address belongs to 1 Customer => One-One Mapping

Java Learning Center 68 Hibernate Study Guide


2) One-Many Relationship

 Consider Relation between Customer and Order

First Direction: Customer => Order (Uni-Directional)


1 Customer can place many Orders => One-Many Mapping

Second Direction: Order => Customer (Bi-Directional)


1 Order belongs to 1 Customer => One-One Mapping

3) Many-Many Relationship

 Consider Relation between Author and Book

First Direction: Author => Book (Uni-Directional)


1 Author can write many Books => One-Many Mapping

Second Direction: Book => Author (Bi-Directional)


1 Book written by many Authors => One-Many Mapping

One-One Uni-Directional Mapping


 Consider the relationship between Customer and Address.
o One Customer contains One Address.
o One Address belongs to One Customer.

A)Tables Required

1) customers
cid cname email phone myaddId
1 Sri [email protected] 99999

2) addresses

addId street city state


1 BTM Blore KA

Java Learning Center 69 Hibernate Study Guide


B) Hibernate Persistence Classes

1) Customer.java

@Entity
@Table(name="customers")
public class Customer{

@OneToOne
@JoinColumn(name="myaddId")
Address address;
}

2)Address.java

@Entity
@Table(name="addresses")
class Address{
....
}

Lab 7: One-One Uni-Directional Mapping Example


Lab7: Files Required:
1. Lab7A.java 2. Lab7B.java
3. Lab7C.java 4. Lab7D.java
5. Lab7E.java 6. Lab7F.java
7. Lab7G.java 8. Lab7H.java
9. Customer.java 10. Address.java
11. HibernateUtil.java*

1)Lab7A.java
package com.jlcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */

public class Lab7A {


public static void main(String[] args) {

Java Learning Center 70 Hibernate Study Guide


Transaction tx = null;
Session session = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

//Provided Both Customer Info and Addrees Info

Address add = new Address("BTM Layout", "Blore", "KA");


session.save(add);

Customer cust = new Customer("Sri", "Sri@jlc", 555);


session.save(cust);

tx.commit();
} catch (Exception ex) {
tx.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
}

2)Lab7B.java
package com.jlcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */

public class Lab7B {


public static void main(String[] args) {

Transaction tx = null;
Session session = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

Java Learning Center 71 Hibernate Study Guide


//Provided Both Customer Info and Addrees Info

Address add = new Address("BTM Layout", "Blore", "KA");


session.save(add);

Customer cust = new Customer("Sri", "Sri@jlc", 555,add);


session.save(cust);

tx.commit();
} catch (Exception ex) {
tx.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
}

3)Lab7C.java
package com.jlcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */
public class Lab7C {
public static void main(String[] args) {
Transaction tx = null;
Session session = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

//Provided Both Customer Info and Addrees Info

Address add = new Address("BTM Layout", "Blore", "KA");


session.save(add);

Customer cust = new Customer("Sri", "Sri@jlc", 555);


session.save(cust);

cust.setAddress(add); //IMP

tx.commit();
} catch (Exception ex) {

Java Learning Center 72 Hibernate Study Guide


tx.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
}

4)Lab7D.java
package com.jlcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */
public class Lab7D {
public static void main(String[] args) {

Transaction tx = null;
Session session = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();
/*
// Not Provided Address
Customer cust = new Customer("aaa", "aaa@jlc", 111);
session.save(cust);
*/

//Provided Address Later


Address add = new Address("BTM Layout", "Blore", "KA");
session.save(add);

Customer cust = session.load(Customer.class, 4);


cust.setAddress(add); //IMP

tx.commit();
} catch (Exception ex) {
tx.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}

Java Learning Center 73 Hibernate Study Guide


}
}

5)Lab7E.java
package com.jlcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */

public class Lab7E {


public static void main(String[] args) {

Transaction tx = null;
Session session = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

//Assigning Existing Address to Existing Customer

Customer cust = session.load(Customer.class, 1);


Address add= session.load(Address.class, 1);

cust.setAddress(add); //IMP

tx.commit();
} catch (Exception ex) {
tx.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
}

Java Learning Center 74 Hibernate Study Guide


6)Lab7F.java
package com.jlcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */

public class Lab7F {


public static void main(String[] args) {

Transaction tx = null;
Session session = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

Customer cust = session.load(Customer.class, 1);


System.out.println(cust);

Address add=cust.getAddress();
System.out.println(add);

tx.commit();
} catch (Exception ex) {
tx.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
}

7)Lab7G.java
package com.jlcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */

Java Learning Center 75 Hibernate Study Guide


public class Lab7G {
public static void main(String[] args) {

Transaction tx = null;
Session session = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

Address add = session.load(Address.class, 1);


System.out.println(add);

//No Way to Customer Info as It is Uni-Directional

tx.commit();
} catch (Exception ex) {
tx.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
}

8)Lab7H.java
package com.jlcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */

public class Lab7H {


public static void main(String[] args) {

Transaction tx = null;
Session session = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

Java Learning Center 76 Hibernate Study Guide


Customer cust = session.load(Customer.class, 3);
session.delete(cust);

tx.commit();
} catch (Exception ex) {
tx.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
}

9)Customer.java
package com.jlcindia.hibernate;

import javax.persistence.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */
@Entity
@Table(name="mycustomers")
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="cid")
private int cid;

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

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

@Column(name="phone")
private int phone;

@OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)


@JoinColumn(name="myaddId")
private Address address;

Java Learning Center 77 Hibernate Study Guide


public Customer() {}

public Customer(String cname, String email, int phone) {


super();
this.cname = cname;
this.email = email;
this.phone = phone;
}

public Customer(int cid, String cname, String email, int phone) {


super();
this.cid = cid;
this.cname = cname;
this.email = email;
this.phone = phone;
}

public Customer(String cname, String email, int phone,Address address) {


this.cname = cname;
this.email = email;
this.phone = phone;
this.address=address;
}

public Customer(int cid, String cname, String email, int phone,Address address) {
this.cid = cid;
this.cname = cname;
this.email = email;
this.phone = phone;
this.address=address;
}
//Constrcutors
//Setters and Getters
//toString()
}

Java Learning Center 78 Hibernate Study Guide


10)Address.java
package com.jlcindia.hibernate;

import javax.persistence.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */
@Entity
@Table(name="myaddresses")
public class Address {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="addId")
private int addId;

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

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

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

public Address() {}

public Address(String street, String city, String state) {


this.street = street;
this.city = city;
this.state = state;
}

public Address(int addId, String street, String city, String state) {


this.addId = addId;
this.street = street;
this.city = city;
this.state = state;
}

//Constrcutors
//Setters and Getters
//toString()

Java Learning Center 79 Hibernate Study Guide


One-One Bi-Directional Mapping
 Consider the relationship between Customer and Address.
o One Customer contains One Address.
o One Address belongs to One Customer.

A)Tables Required

1) customers
cid cname email phone myaddId
1 Sri [email protected] 99999

2) addresses

addId street city state


1 BTM Blore KA

B) Hibernate Persistence Classes

1) Customer.java

@Entity
@Table(name="customers")
public class Customer{

@OneToOne
@JoinColumn(name="myaddId")
Address address;
}

2)Address.java

@Entity
@Table(name="addresses")
class Address{
....
@OneToOne(mappedBy = "address")
Customer customer;

Java Learning Center 80 Hibernate Study Guide


Lab 8: One-One Bi-Directional Mapping Example
Lab8: Files Required:
1. Lab8A.java Same as Lab7A
2. Lab8B.java Same as Lab7B
3. Lab8C.java Same as Lab7C
4. Lab8D.java Same as Lab7D
5. Lab8E.java Same as Lab7E
6. Lab8F.java Same as Lab7F
7. Lab8G.java Updated in Lab8
8. Lab8H.java Same as Lab7H
9. Lab8I.java Newly Added in Lab8
10. Customer.java Same as Lab7
11. Address.java Updated in Lab8
12. HibernateUtil.java* Same as Lab7

7)Lab8G.java
package com.jlcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */
public class Lab7G {
public static void main(String[] args) {

Transaction tx = null;
Session session = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

Address add = session.load(Address.class, 1);


System.out.println(add);

Customer cust = add.getCustomer();


System.out.println(cust);

tx.commit();
} catch (Exception ex) {
tx.rollback();
ex.printStackTrace();

Java Learning Center 81 Hibernate Study Guide


} finally {
if (session != null)
session.close();
}
}
}

9)Lab8I.java
package com.jlcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */

public class Lab8I {


public static void main(String[] args) {

Transaction tx = null;
Session session = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();

Address add = session.load(Address.class,1);


session.delete(add);

tx.commit();
} catch (Exception ex) {
tx.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}
}
}

Java Learning Center 82 Hibernate Study Guide


11)Address.java
package com.jlcindia.hibernate;

import javax.persistence.*;
/*
* @Author : Srinivas Dande
* @Company: Java Learning Center
* */
@Entity
@Table(name="myaddresses")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="addId")
private int addId;

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

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

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

@OneToOne(mappedBy = "address",fetch = FetchType.LAZY)


private Customer customer;

public Address() {}
public Address(String street, String city, String state) {
this.street = street;
this.city = city;
this.state = state;
}
public Address(int addId, String street, String city, String state) {
this.addId = addId;
this.street = street;
this.city = city;
this.state = state;
}

//Constrcutors
//Setters and Getters
//toString()
}

Java Learning Center 83 Hibernate Study Guide


Interview Questions:
Q71) When to Use Association Mapping?
Ans:

Q72) What is Cardinality?


Ans:

Q73) How many ways to implement Association Mapping based on Cardinality?


Ans:

Q74) What is Directionality?


Ans:

Q75) How many ways to implement Association Mapping based on Directionality?


Ans:

Q76) What is the difference between Uni-Directional and Bi-Directional Relationship?


Ans:

Q77) What are the Annotations to be used for First Side Entity Class in One-One Mapping?
Ans:

Q78) What are the Annotations to be used for Second Side Entity Class in One-One Mapping?
Ans:

Q79) Which Table should have the F.K I in One-One Mapping?


Ans:

Q80) What is the Default Loading Strategy used for One-One Mapping?
Ans:

Java Learning Center 84 Hibernate Study Guide


Q81) What is the Default Fetching Strategy used for One-One Mapping?
Ans:

Q82) What is the Default Cascade Style used for One-One Mapping?
Ans:

Q83) How to specify the Required Loading Strategy used for One-One Mapping?
Ans:

Q84) How to specify the Required Fetching Strategy used for One-One Mapping?
Ans:

Q85) How to specify the Required Cascade Style used for One-One Mapping?
Ans:

Q86) What is the speciality of customer.setAddress(address)?


Ans:

Java Learning Center 85 Hibernate Study Guide


One-Many Bi-Directional Mapping

 Consider the relationship between Customer and Request.


o One Customer can place Many Requests.
o One Request belongs to One Customer only.

A)Tables Required

1) mycustomers
cid cname email phone
1 Sri [email protected] 99999

2) myaccounts
accno atype acode bal mycid
1 SA BC-109 20000 1
2 DA BC-199 25000 1

B) Hibernate Persistence Classes

1) Customer.java
@Entity
@Table(name = "mycustomers")
public class Customer {

@OneToMany(mappedBy = "customer")
private Set< Account > accounts;
...
}

2) Account.java
@Entity
@Table(name = "myaccounts")
public class Account {

@ManyToOne
@JoinColumn(name="mycid",referencedColumnName="cid")
Customer customer;
...
}

Java Learning Center 86 Hibernate Study Guide


Lab9: Files required
1. Lab9A.java 2. Lab9B.java
3. Lab9C.java 4. Lab9D.java
5. Lab9E.java 6. Lab9F.java
7. Customer.java 8. Account.java
9. HibernateUtil.java***

1. Lab9A.java 2. Lab9B.java
package com.jlcindia.hibernate; package com. jlcindia.hibernate;

import org.hibernate.*; import org.hibernate.*;


/* /*
* @Author : Srinivas Dande * @Author : Srinivas Dande
* @Company: Java Learning Center * @Company: Java Learning Center
* */ * */
public class Lab9A { public class Lab9B {
public static void main(String[] args) { public static void main(String[] args) {
Transaction tx=null; Transaction tx=null;
try { try {
SessionFactory SessionFactory
sf=HibernateUtil.getSessionFactory(); sf=HibernateUtil.getSessionFactory();
Session session=sf.openSession(); Session session=sf.openSession();
tx=session.beginTransaction(); tx=session.beginTransaction();

Customer cust=new Customer cust=new


Customer("sri","[email protected]",12345); Customer("vas","[email protected]",12345);
session.save(cust); session.save(cust);

Account acc1=new Account("SA","BC- Account acc1=new Account("SA","BC-


101",25000); 101",25000);
session.save(acc1); session.save(acc1);

Account acc2=new Account("SA","BC-102",5000); acc1.setCustomer(cust);


session.save(acc2);
Account acc2=new Account("SA","BC-102",5000);
tx.commit(); session.save(acc2);
session.close();
acc2.setCustomer(cust);
}catch(Exception ex) { tx.commit();
ex.printStackTrace(); session.close();
if(tx!=null) }catch(Exception ex) {
tx.rollback(); ….
} }
} }
} }

Java Learning Center 87 Hibernate Study Guide


3. Lab9C.java 4. Lab9D.java
package com. jlcindia.hibernate; package com. jlcindia.hibernate;

import org.hibernate.*; import java.util.Set;


/* import org.hibernate.*;
* @Author : Srinivas Dande /*
* @Company: Java Learning Center * @Author : Srinivas Dande
* */ * @Company: Java Learning Center
public class Lab9C { * */
public static void main(String[] args) { public class Lab9D {
Transaction tx=null; public static void main(String[] args) {
try { Transaction tx=null;
SessionFactory try {
sf=HibernateUtil.getSessionFactory(); SessionFactory
Session session=sf.openSession(); sf=HibernateUtil.getSessionFactory();
tx=session.beginTransaction(); Session session=sf.openSession();
tx=session.beginTransaction();
Customer cust=session.load(Customer.class,1);
System.out.println(cust); Customer cust=session.load(Customer.class,1);
System.out.println(cust);
Account acc1=new Account("DA","BC-
190",5000); Set<Account> accs=cust.getAccounts();
session.save(acc1); for(Account acc:accs)
System.out.println(acc);
acc1.setCustomer(cust);
tx.commit();
tx.commit(); session.close();
session.close();
}catch(Exception ex) {
}catch(Exception ex) { ex.printStackTrace();
ex.printStackTrace(); if(tx!=null)
if(tx!=null) tx.rollback();
tx.rollback(); }
} }
} }
}

Java Learning Center 88 Hibernate Study Guide


5. Lab9E.java 6. Lab9F.java
package com. jlcindia.hibernate; package com. jlcindia.hibernate;

import org.hibernate.*; import org.hibernate.*;


/* /*
* @Author : Srinivas Dande * @Author : Srinivas Dande
* @Company: Java Learning Center * @Company: Java Learning Center
* */ * */
public class Lab9E { public class Lab9F {
public static void main(String[] args) { public static void main(String[] args) {
Transaction tx=null; Transaction tx=null;
try { try {
SessionFactory SessionFactory
sf=HibernateUtil.getSessionFactory(); sf=HibernateUtil.getSessionFactory();
Session session=sf.openSession(); Session session=sf.openSession();
tx=session.beginTransaction(); tx=session.beginTransaction();

Account acc=session.load(Account.class,3); Customer cust=session.load(Customer.class,3);


System.out.println(acc); session.delete(cust);

Customer cust=acc.getCustomer(); tx.commit();


System.out.println(cust); session.close();

tx.commit(); }catch(Exception ex) {


session.close(); ex.printStackTrace();
if(tx!=null)
}catch(Exception ex) { tx.rollback();
ex.printStackTrace(); }
if(tx!=null)
tx.rollback(); }
} }

}
}

Java Learning Center 89 Hibernate Study Guide


7. Customer.java 8. Account.java
package com. jlcindia.hibernate; package com. jlcindia.hibernate;

import java.util.*; import javax.persistence.*;


import javax.persistence.*; /*
/* * @Author : Srinivas Dande
* @Author : Srinivas Dande * @Company: Java Learning Center
* @Company: Java Learning Center * */
* */ @Entity
@Entity @Table(name="myaccounts")
@Table(name="mycustomers") public class Account {
public class Customer { @Id
@GeneratedValue(strategy =
@Id GenerationType.IDENTITY)
@GeneratedValue(strategy = @Column(name="accno")
GenerationType.IDENTITY) private int accno;
@Column(name="cid")
private int cid; @Column(name="atype")
private String atype;
@Column(name="cname")
private String cname; @Column(name="bcode")
private String bcode;
@Column(name="email")
private String email; @Column(name="bal")
private double bal;
@Column(name="phone")
private long phone; @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="mycid",referencedColu
@OneToMany(mappedBy = mnName = "cid")
"customer",fetch=FetchType.LAZY,cascade = private Customer customer;
CascadeType.ALL)
private Set<Account> accounts; public Account() {}

public Customer() {} public Account(String atype, String bcode, double


public Customer(String cname, String email, long bal) {
phone) { super();
this.cname = cname; this.atype = atype;
this.email = email; this.bcode = bcode;
this.phone = phone; this.bal = bal;
} }
//Setters and Getters //Setters and Getters
@Override @Override
public String toString() { public String toString() {
return cid + "\t" + cname + "\t" + email + "\t" + return accno + "\t" + atype + "\t" + bcode + "\t" +
phone ; bal ;
} }
} }

Java Learning Center 90 Hibernate Study Guide


Many-Many Bi-Directional Mapping

 Consider the relationship between Student and Course


o One Student can join for many Courses.
o One Course can have Many Students

A)Tables Required
1) mystudents
sid sname email phone

2) mycourses
cid cname cost trainer

3) stu_cou
mycid mysid

B) Hibernate Persistence Classes


1) Student.java
@Entity
@Table(name = "jlcstudents")
public class Student {

@ManyToMany
@JoinTable(name = "stu_cou",
joinColumns =
@JoinColumn(name = "sid", referencedColumnName ="sid"),
inverseJoinColumns =
@JoinColumn(name = "cid", referencedColumnName="cid"))
private Set<Course> courses;
}

2)Course.java

@Entity
@Table(name = "jlccourses")
public class Course {
@ManyToMany(mappedBy = "courses")
private Set<Student> students;
}

Java Learning Center 91 Hibernate Study Guide


Lab10: Files required
1. Lab10A.java 2. Lab10B.java
3. Lab10C.java 4. Lab10D.java
5. Lab10E.java 6. Lab10F.java
7. Lab10G.java 8. Lab10H.java
9. Lab10I.java 10. Student.java
11. Course.java 12. HibernateUtil.java

1. Lab10A.java 2. Lab10B.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

import org.hibernate.*; import java.util.*;


/* import org.hibernate.*;
* @Author : Srinivas Dande
* @Company: Java Learning Center public class Lab10B {
* */ public static void main(String[] args) {
public class Lab10A { Transaction tx=null;
public static void main(String[] args) { try {
Transaction tx=null; SessionFactory
try { sf=HibernateUtil.getSessionFactory();
SessionFactory Session session=sf.openSession();
sf=HibernateUtil.getSessionFactory(); tx=session.beginTransaction();
Session session=sf.openSession();
tx=session.beginTransaction(); Course cou1=new Course("Master
Java",10000,"Srinivas");
Student stu1=new session.save(cou1);
Student("sri","[email protected]",12345); Course cou2=new Course("Master
session.save(stu1); Hibernate5",10000,"Srinivas");
Student stu2=new session.save(cou2);
Student("aa","[email protected]",12345); Course cou3=new Course("Master
session.save(stu2); Spring5",10000,"Srinivas");
Student stu3=new session.save(cou3);
Student("vas","[email protected]",12345);
session.save(stu3); Student stu1=new
Student("sri","[email protected]",12345);
Course cou1=new Course("Master session.save(stu1);
Java",10000,"Srinivas");
session.save(cou1); Set<Course> cous=new HashSet<>();
Course cou2=new Course("Master cous.add(cou1); cous.add(cou2);
Hibernate5",10000,"Srinivas"); cous.add(cou3);
session.save(cou2); stu1.setCourses(cous);
Course cou3=new Course("Master
Spring5",10000,"Srinivas"); Student stu2=new
session.save(cou3); Student("aa","[email protected]",12345);
session.save(stu2);

tx.commit(); cous=new HashSet<>();

Java Learning Center 92 Hibernate Study Guide


session.close(); cous.add(cou2); cous.add(cou3);
}catch(Exception ex) { stu2.setCourses(cous);
ex.printStackTrace();
if(tx!=null) Student stu3=new
tx.rollback(); Student("vas","[email protected]",12345);
} session.save(stu3);
}
} cous=new HashSet<>();
cous.add(cou1); cous.add(cou3);
stu3.setCourses(cous);

tx.commit();
session.close();
}catch(Exception ex) {
ex.printStackTrace();
if(tx!=null)
tx.rollback();
} }
}
3. Lab10C.java 4. Lab10D.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

import java.util.*; import java.util.*;


import org.hibernate.*; import org.hibernate.*;
/* /*
* @Author : Srinivas Dande * @Author : Srinivas Dande
* @Company: Java Learning Center * @Company: Java Learning Center
* */ * */
public class Lab10C { public class Lab10D {
public static void main(String[] args) { public static void main(String[] args) {
Transaction tx=null; Transaction tx=null;
try { try {
SessionFactory SessionFactory
sf=HibernateUtil.getSessionFactory(); sf=HibernateUtil.getSessionFactory();
Session session=sf.openSession(); Session session=sf.openSession();
tx=session.beginTransaction(); tx=session.beginTransaction();

Student stu=new Student stu=session.load(Student.class, 5);


Student("dd","[email protected]",12345);
session.save(stu); Course cou=session.load(Course.class, 3);

Course cou=session.load(Course.class, 3); Set<Course> cous=stu.getCourses();


cous.add(cou);
Set<Course> cous=new HashSet<>();
cous.add(cou); stu.setCourses(cous);

stu.setCourses(cous); tx.commit();
session.close();

Java Learning Center 93 Hibernate Study Guide


tx.commit();
session.close(); }catch(Exception ex) {
ex.printStackTrace();
}catch(Exception ex) { if(tx!=null)
ex.printStackTrace(); tx.rollback();
if(tx!=null) }
tx.rollback(); }
} }
} }

5. Lab10E.java 6. Lab10F.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

import java.util.*; import java.util.*;


import org.hibernate.*; import org.hibernate.*;
/* /*
* @Author : Srinivas Dande * @Author : Srinivas Dande
* @Company: Java Learning Center * @Company: Java Learning Center
* */ * */
public class Lab10E { public class Lab10F {
public static void main(String[] args) { public static void main(String[] args) {
Transaction tx=null; Transaction tx=null;
try { try {
SessionFactory SessionFactory
sf=HibernateUtil.getSessionFactory(); sf=HibernateUtil.getSessionFactory();
Session session=sf.openSession(); Session session=sf.openSession();
tx=session.beginTransaction(); tx=session.beginTransaction();

Student stu=session.load(Student.class, 1); Course cou=session.load(Course.class, 3);


System.out.println(stu); System.out.println(cou);

Set<Course> cous=stu.getCourses(); Set<Student> stus=cou.getStudents();


for(Course cou:cous) for(Student stu:stus)
System.out.println(cou); System.out.println(stu);

tx.commit(); tx.commit();
session.close(); session.close();
}catch(Exception ex) { }catch(Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
if(tx!=null) if(tx!=null)
tx.rollback(); tx.rollback();
} }
} }
} }

Java Learning Center 94 Hibernate Study Guide


7. Lab10G.java 9. Lab10H.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

import java.util.*; import java.util.*;


import org.hibernate.*; import org.hibernate.*;
/* /*
* @Author : Srinivas Dande * @Author : Srinivas Dande
* @Company: Java Learning Center * @Company: Java Learning Center
* */ * */
public class Lab10G { public class Lab10H {
public static void main(String[] args) { public static void main(String[] args) {
Transaction tx=null; Transaction tx=null;
try { try {
SessionFactory SessionFactory
sf=HibernateUtil.getSessionFactory(); sf=HibernateUtil.getSessionFactory();
Session session=sf.openSession(); Session session=sf.openSession();
tx=session.beginTransaction(); tx=session.beginTransaction();

Student stu=session.load(Student.class, 1); Course cou=session.load(Course.class, 3);


session.delete(stu); session.delete(cou);

tx.commit(); tx.commit();
session.close(); session.close();
}catch(Exception ex) { }catch(Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
if(tx!=null) if(tx!=null)
tx.rollback(); tx.rollback();
} }
} }
} }

10. Student.java 11. Course.java


package com.coursecube.hibernate; package com.coursecube.hibernate;

import java.util.*; import java.util.Set;


import javax.persistence.*; import javax.persistence.*;
/* /*
* @Author : Srinivas Dande * @Author : Srinivas Dande
* @Company: Java Learning Center * @Company: Java Learning Center
* */ * */
@Entity @Entity
@Table(name="mystudents") @Table(name="mycourses")
public class Student { public class Course {

Java Learning Center 95 Hibernate Study Guide


@Id @Id
@GeneratedValue(strategy = @GeneratedValue(strategy =
GenerationType.IDENTITY) GenerationType.IDENTITY)
@Column(name="sid") @Column(name="cid")
private int sid; private int cid;

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

@Column(name="email") @Column(name="cost")
private String email; private double cost;

@Column(name="phone") @Column(name="trainer")
private long phone; private String trainer;

@ManyToMany @ManyToMany(mappedBy = "courses")


@JoinTable( private Set<Student> students;
name="stu_cou",
joinColumns = public Course() {}
@JoinColumn(name="mysid",referencedColu
mnName = "sid"), public Course(String cname, double cost, String
inverseJoinColumns = trainer) {
@JoinColumn(name="mycid",referencedColu super();
mnName = "cid") this.cname = cname;
) this.cost = cost;
private Set<Course> courses; this.trainer = trainer;
}
public Student() {}
public Student(String sname, String email, long //Setters and Getters
phone) {
this.sname =sname; @Override
this.email = email; public String toString() {
this.phone = phone; return cid + "\t" + cname + "\t" + cost + "\t" +
} trainer ;
}
//Setters and Getters
}
@Override
public String toString() {
return sid + "\t" + sname + "\t" + email + "\t" +
phone ;
}

Java Learning Center 96 Hibernate Study Guide

You might also like