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

Module 6 - Primary Keys and Connection Management (1)

useful 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 views28 pages

Module 6 - Primary Keys and Connection Management (1)

useful 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/ 28

Working with Primary keys

 Primary Key is value which can be used to Identify the each Row Uniquly.
 When you apply Primary key for a Column then two Constraints will be applied.
o Unique Constraint
o NOT NULL Constraint
 Table can have One and Only One Primary Key.
 There are two types of Primary Keys.
1) Simple Primary Key
2) Composite Primary.

1)Simple Primary Key:


 When you specify the Primary key for single Column then it is called as Simple
Primary Key.

 Following is the way to specify the Simple Primary key in Hibernate

class Customer{
@Id
int cid;
}
 Developer or Hibernate System or DB engine are Responsible for provding values
for Primary key filed.

Case 1) Consider the following code.


@Entity
@Table(name="mycustomers1")
public class Customer {
@Id
@Column(name="cid")
private int cid;
...
}

 In the above code , you are not specifying @GeneratedValue annotation.


 So Hibernate System will not suppy the Primary key value and We have to supply the
value for Primary key.

 Q)What happens when I run this client code.


Customer cust=new Customer("sri","[email protected]",12345);
session.save(cust);
Ans: First It inserts One record with 0 as cid value and when you execute this code
again then it gives the error.

Refer Lab21:

Java Learning Center 122 Hibernate5 Study Guide


Case 2) Consider the following code.
@Entity
@Table(name="mycustomers2")
public class Customer {
@Id
@GeneratedValue
@Column(name="cid")
private int cid;
...
}

 In the above code , we are specifying @GeneratedValue annotation without strategy


then Hibernate System uses GenerationType as AUTO by deafult.

Refer Lab22:

Case 3) Consider the following code.


@Entity
@Table(name="mycustomers3")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="cid")
private int cid;
...
}

 In the above code , we are specifying @GeneratedValue annotation with


GenerationType as AUTO.

 If Database supports Sequence then Hibernate System uses the sequence with the
name "hibernate_sequence" for Primary key values.

 If Database does supports Sequence then Hibernate System uses the the table with
the name "hibernate_sequence" for Primary key values.

MySQL: (Lab23)
------------
create table hibernate_sequence (next_val bigint);
insert into hibernate_sequence values ( 101 );

Oracle:(Lab24)
----------
create sequence hibernate_sequence
starts with 101
increment by 1;

Java Learning Center 123 Hibernate5 Study Guide


Case 4) Consider the following code.

Customer.java

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

@Id
@GeneratedValue(strategy = GenerationType.AUTO,generator =
"cid_generator")
@SequenceGenerator(name="cid_generator",sequenceName =
"mycid_gen",initialValue = 101,allocationSize = 1)
@Column(name="cid")
private int cid;
...
}

Student.java

@Entity
@Table(name="students")
public class Student {

@Id
@GeneratedValue(strategy = GenerationType.AUTO,generator =
"sid_generator")
@SequenceGenerator(name="sid_generator",sequenceName =
"mysid_gen",initialValue = 501,allocationSize = 1)
@Column(name="sid")
private int sid;
...
}

 In the above code , we are specifying @GeneratedValue annotation with


GenerationType as AUTO.

 We are specifying different tables for holding the Primar keys of Students and
Customers by using @SequenceGenerator.

Refer Lab25

Java Learning Center 124 Hibernate5 Study Guide


Case 5) Consider the following code.
Customer.java

@Entity
@Table(name="customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator =
"cid_generator")
@SequenceGenerator(name="cid_generator",sequenceName =
"mycid_gen",initialValue = 101,allocationSize = 1)
@Column(name="cid")
private int cid;
...
}

Student.java

@Entity
@Table(name="students")
public class Student {

@Id
@GeneratedValue(strategy = GenerationType.TABLE,generator =
"sid_generator")
@TableGenerator(name="sid_generator",table= "mysid_gen",initialValue =
501,allocationSize = 1)
@Column(name="sid")
private int sid;
...
}

 In the above code , we are specifying @GeneratedValue annotation with


GenerationType as SEQUENCE.

 We are specifying table name for holding the Primar key Customers with
@SequenceGenerator

 We are specifying table name for holding the Primar key Students with
@TableGenerator

Refer Lab26

Java Learning Center 125 Hibernate5 Study Guide


Case 6) Consider the following code.
@Entity
@Table(name="mycustomers")
public class Customer {

@Id
@GeneratedValue(generator = "cid_generator")
@GenericGenerator(name = "cid_generator",strategy =
"org.hibernate.id.UUIDHexGenerator")
@Column(name="cid")
private String cid;

}

 In the Above Code , You are using UUIDHexGenerator

Refer Lab27

Developing Custom Generators:


 Depending on wthere you want to provide the value for Primary key field or
hibernate has to provide the value

Case 7) Consider the following code.


 I want Generate the Primary Key and I want to provide the value for Primary key
Field
Customer.java
public class Customer {
@Id
@Column(name="cid")
private int cid;
..
}
CIDGenerator.java
public class CIDGenerator {
public static Serializable getNextCustomerId() {
//Your Logic Here
}
}

Client Code
String cid=(String)CIDGenerator.getNextCustomerId();
Customer cust=new Customer(cid,"sri","[email protected]",12345);
session.save(cust);

Refer Lab28

Java Learning Center 126 Hibernate5 Study Guide


Case 8) Consider the following code.
 I want Generate the Primary Key and Hibernate System has to provide the value for
Primary key field
Customer.java
public class Customer {
@Id
@GeneratedValue(generator = "cid_generator")
@GenericGenerator(name="cid_generator",strategy =
"com.coursecube.hibernate.CIDGenerator")
@Column(name="cid")
private String cid;..
}
CIDGenerator.java
public class CIDGenerator implements IdentifierGenerator{
@Override
public Serializable generate(SharedSessionContractImplementor sessionImpl,
Object obj) throws HibernateException {
//Your Logic Here
}
}
Client Code
Customer cust=new Customer("sri","[email protected]",12345);
session.save(cust);

Refer Lab29

Java Learning Center 127 Hibernate5 Study Guide


Lab21: Without @GeneratedValue

Lab21: Files required


1. Lab21.java 2. Customer.java
3. HibernateUtil.java

1. Lab21.java 2. Customer.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

import org.hibernate.*; import javax.persistence.*;


/* /*
* @Author : Srinivas Dande * @Author : Srinivas Dande
* @company : Java Learning Center * @company : Java Learning Center
* */ * */
public class Lab21 { @Entity
public static void main(String[] args) { @Table(name="mycustomers1")
Transaction tx=null; public class Customer {
try {
SessionFactory sf=HibernateUtil.getSessionFactory(); @Id
Session session=sf.openSession(); @Column(name="cid")
tx=session.beginTransaction(); private int cid;

Customer cust=new @Column(name="cname")


Customer(101,"sri","[email protected]",12345); private String cname;
session.save(cust);
@Column(name="email")
tx.commit(); private String email;
session.close();
@Column(name="phone")
}catch(Exception ex) { private long phone;
ex.printStackTrace();
if(tx!=null) public Customer() {}
tx.rollback(); public Customer(int cid, String cname, String email, long
} phone) {
this.cid = cid;
} this.cname = cname;
} this.email = email;
this.phone = phone;
}
//Setters and Getters

@Override
public String toString() {
return cid + "\t" + cname + "\t" + email + "\t" + phone ;
}
}

Java Learning Center 128 Hibernate5 Study Guide


Lab22: With @GeneratedValue and without Any Strategy

Lab22: Files required


1. Lab22.java 2. Customer.java
3. HibernateUtil.java

1. Lab22.java 2. Customer.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

import org.hibernate.*; import javax.persistence.*;


/* /*
* @Author : Srinivas Dande * @Author : Srinivas Dande
* @company : Java Learning Center * @company : Java Learning Center
* */ * */
public class Lab22 { @Entity
public static void main(String[] args) { @Table(name="mycustomers2")
Transaction tx=null; public class Customer {
try {
SessionFactory sf=HibernateUtil.getSessionFactory(); @Id
Session session=sf.openSession(); @GeneratedValue
tx=session.beginTransaction(); @Column(name="cid")
private int cid;
Customer cust=new
Customer("sri","[email protected]",12345); @Column(name="cname")
session.save(cust); private String cname;

tx.commit(); @Column(name="email")
session.close(); private String email;

}catch(Exception ex) { @Column(name="phone")


ex.printStackTrace(); private long phone;
if(tx!=null)
tx.rollback(); public Customer() {}
} public Customer(String cname, String email, long phone)
{
} this.cname = cname;
} this.email = email;
this.phone = phone;
}
//Setters and Getters

@Override
public String toString() {
return cid + "\t" + cname + "\t" + email + "\t" + phone ;
}
}

Java Learning Center 129 Hibernate5 Study Guide


Lab23: With GenerationType.AUTO (MySQL)

Lab23: Files required


1. Lab23.java 2. Customer.java
3. HibernateUtil.java

1. Lab23.java 2. Customer.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

import org.hibernate.*; import javax.persistence.*;


/* /*
* @Author : Srinivas Dande * @Author : Srinivas Dande
* @company : Java Learning Center * @company : Java Learning Center
* */ * */
public class Lab23 { @Entity
public static void main(String[] args) { @Table(name="mycustomers3")
Transaction tx=null; public class Customer {
try {
SessionFactory sf=HibernateUtil.getSessionFactory(); @Id
Session session=sf.openSession(); @GeneratedValue(strategy = GenerationType.AUTO)
tx=session.beginTransaction(); @Column(name="cid")
private int cid;
Customer cust=new
Customer("sri","[email protected]",12345); @Column(name="cname")
session.save(cust); private String cname;

tx.commit(); @Column(name="email")
session.close(); private String email;

}catch(Exception ex) { @Column(name="phone")


ex.printStackTrace(); private long phone;
if(tx!=null)
tx.rollback(); public Customer() {}
} public Customer(String cname, String email, long phone)
{
} this.cname = cname;
} this.email = email;
this.phone = phone;
}
//Setters and Getters

@Override
public String toString() {
return cid + "\t" + cname + "\t" + email + "\t" + phone ;
}
}

Java Learning Center 130 Hibernate5 Study Guide


Lab24: With GenerationType.AUTO (Oracle)

Lab24: Files required


1. Lab24.java (Same as Lab23) 2. Customer.java (Same as Lab23)
3. HibernateUtil.java

1. HibernateUtil.java
package com.coursecube.hibernate;

import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
/*
* @Author : Srinivas Dande
* @company : Java Learning Center
* */
public class HibernateUtil {
static SessionFactory sessionFactory;
static {
Configuration cfg=new Configuration();

Properties props=new Properties();


props.put(Environment.DRIVER, "oracle.jdbc.driver.OracleDriver");
props.put(Environment.URL, "jdbc:oracle:thin:@localhost:1521:XE");
props.put(Environment.USER, "system");
props.put(Environment.PASS, "srinivas");

props.put(Environment.SHOW_SQL, "true");
props.put(Environment.DIALECT, "org.hibernate.dialect.Oracle10gDialect");

props.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
props.put(Environment.HBM2DDL_AUTO, "update");

cfg.setProperties(props);

cfg.addAnnotatedClass(Customer.class);

StandardServiceRegistryBuilder ssrbuilder=new StandardServiceRegistryBuilder();


ServiceRegistry serviceReg=ssrbuilder.applySettings(cfg.getProperties()).build();
sessionFactory=cfg.buildSessionFactory(serviceReg);
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Java Learning Center 131 Hibernate5 Study Guide


Lab25: With GenerationType.AUTO with Custom Tables
Lab25: Files required
1. Lab25.java 2. Customer.java
3. Student.java 4. HibernateUtil.java

1. Lab25.java @Column(name="cname")
package com.coursecube.hibernate; private String cname;

import org.hibernate.*; @Column(name="email")


public class Lab25 { private String email;
public static void main(String[] args) {
Transaction tx=null; @Column(name="phone")
try { private long phone;
SessionFactory sf=HibernateUtil.getSessionFactory(); //Constrcutors
Session session=sf.openSession(); //Setters and Getters
tx=session.beginTransaction(); //toString() method
}
Customer cust=new Customer("sri","[email protected]",999); 3. Student.java
session.save(cust); package com.coursecube.hibernate;

Student stu=new Student("vas","[email protected]",555); import javax.persistence.*;


session.save(stu);
@Entity
tx.commit(); @Table(name="students")
session.close(); public class Student {
}catch(Exception ex) {
ex.printStackTrace(); @Id
if(tx!=null) @GeneratedValue(strategy =
tx.rollback(); GenerationType.AUTO,generator = "sid_generator")
} } } @SequenceGenerator(name="sid_generator",sequence
2. Customer.java Name = "mysid_gen",initialValue = 501,allocationSize =
package com.coursecube.hibernate; 1)
@Column(name="sid")
import javax.persistence.*; private int sid;
@Entity
@Table(name="customers") @Column(name="sname")
public class Customer { private String sname;

@Id @Column(name="email")
@GeneratedValue(strategy = private String email;
GenerationType.AUTO,generator = "cid_generator")
@SequenceGenerator(name="cid_generator",sequence @Column(name="phone")
Name = "mycid_gen",initialValue = 101,allocationSize = private long phone;
1) //Constrcutors
@Column(name="cid") //Setters and Getters
private int cid; //toString() method
}

Java Learning Center 132 Hibernate5 Study Guide


Lab26: GenerationType.SEQUENCE & GenerationType.TABLE
Lab26: Files required
1. Lab26.java 2. Customer.java
3. Student.java 4. HibernateUtil.java

1. Lab26.java @Column(name="cname")
package com.coursecube.hibernate; private String cname;

import org.hibernate.*; @Column(name="email")


public class Lab26 { private String email;
public static void main(String[] args) {
Transaction tx=null; @Column(name="phone")
try { private long phone;
SessionFactory sf=HibernateUtil.getSessionFactory(); //Constrcutors
Session session=sf.openSession(); //Setters and Getters
tx=session.beginTransaction(); //toString() method
}
Customer cust=new Customer("sri","[email protected]",999); 3. Student.java
session.save(cust); package com.coursecube.hibernate;

Student stu=new Student("vas","[email protected]",555); import javax.persistence.*;


session.save(stu);
@Entity
tx.commit(); @Table(name="students")
session.close(); public class Student {
}catch(Exception ex) {
ex.printStackTrace(); @Id
if(tx!=null) @GeneratedValue(strategy =
tx.rollback(); GenerationType.TABLE,generator = "sid_generator")
} } } @TableGenerator(name="sid_generator",table =
2. Customer.java "mysid_gen",initialValue = 801,allocationSize = 1)
package com.coursecube.hibernate; @Column(name="sid")
private int sid;
import javax.persistence.*;
@Entity @Column(name="sname")
@Table(name="customers") private String sname;
public class Customer {
@Column(name="email")
@Id private String email;
@GeneratedValue(strategy =
GenerationType.SEQUENCE,generator = @Column(name="phone")
"cid_generator") private long phone;
@SequenceGenerator(name="cid_generator",sequence //Constrcutors
Name = "mycid_gen",initialValue = 201,allocationSize = //Setters and Getters
1) //toString() method
@Column(name="cid") }
private int cid;

Java Learning Center 133 Hibernate5 Study Guide


Lab27: Using UUIDHexGenerator

Lab27: Files required


1. Lab27.java 2. Customer.java
3. HibernateUtil.java

1. Lab27.java 2. Customer.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

import org.hibernate.*; import javax.persistence.*;


/* import org.hibernate.annotations.GenericGenerator;
* @Author : Srinivas Dande /*
* @company : Java Learning Center * @Author : Srinivas Dande
* */ * @company : Java Learning Center
public class Lab27 { * */
public static void main(String[] args) { @Entity
Transaction tx=null; @Table(name="mycustomers")
try { public class Customer {
SessionFactory sf=HibernateUtil.getSessionFactory();
Session session=sf.openSession(); @Id
tx=session.beginTransaction(); @GeneratedValue(generator = "cid_generator")
@GenericGenerator(name = "cid_generator",strategy =
Customer cust=new "org.hibernate.id.UUIDHexGenerator")
Customer("sri","[email protected]",12345); @Column(name="cid")
session.save(cust); private String cid;

tx.commit(); @Column(name="cname")
session.close(); private String cname;

}catch(Exception ex) { @Column(name="email")


ex.printStackTrace(); private String email;
if(tx!=null)
tx.rollback(); @Column(name="phone")
} private long phone;

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

Java Learning Center 134 Hibernate5 Study Guide


Lab28: Using Custom Primary Key Generation
Lab28: Files required
1. Lab28.java 2. Customer.java
3. CIDGenerator.java 4. HibernateUtil.java

1. Lab28.java public Customer(String cid, String cname, String email, long


package com.coursecube.hibernate; phone) {
this.cid = cid;
import org.hibernate.*; this.cname = cname;
public class Lab28 { this.email = email;
public static void main(String[] args) { this.phone = phone;
Transaction tx=null; }
try { @Override
SessionFactory sf=HibernateUtil.getSessionFactory(); public String toString() {
Session session=sf.openSession(); return cid + "\t" + cname + "\t" + email + "\t" + phone;
tx=session.beginTransaction(); } }
String 3. CIDGenerator.java
cid=(String)CIDGenerator.getNextCustomerID(session); package com.coursecube.hibernate;
Customer stu=new
Customer(cid,"sri","[email protected]",99999); import java.io.*;
session.save(stu); import org.hibernate.*;
tx.commit(); public class CIDGenerator {
session.close();
}catch(Exception ex) { public static Serializable getNextCustomerID(Session
ex.printStackTrace(); session){
if(tx!=null) System.out.println("CIDGenerator-getNextCustomerID()");
tx.rollback(); String cid="C-001";
}}} try {
2. Customer.java String HQL="select max(cust.cid) from Customer cust";
package com.coursecube.hibernate; String
id=session.createQuery(HQL,String.class).uniqueResult();
import javax.persistence.*; if(id!=null) {
@Entity String p2=id.substring(2);
@Table(name="mycustomers") int x=Integer.parseInt(p2);
public class Customer { x=x+1;
@Id if(x<=9)
@Column(name="cid") cid="C-00"+x;
private String cid; else if(x<=99)
cid="C-0"+x;
@Column(name="cname") else if(x<=999)
private String cname; cid="C-"+x;
}
@Column(name="email") }catch(Exception ex) {
private String email; ex.printStackTrace();
}
@Column(name="phone") return cid;
private long phone; }
}
public Customer() { }

Java Learning Center 135 Hibernate5 Study Guide


Lab29: Using Custom Primary Key Generation
Lab29: Files required
1. Lab29.java 2. Customer.java
3. CIDGenerator.java 4. HibernateUtil.java

1. Lab29.java @Column(name="phone")
package com.coursecube.hibernate; private long phone;
public Customer() { }
import org.hibernate.*; public Customer(String cname, String email, long phone) {
public class Lab29 { this.cname = cname;
public static void main(String[] args) { this.email = email;
Transaction tx=null; this.phone = phone;
try { }
SessionFactory sf=HibernateUtil.getSessionFactory(); //Setters and Getters
Session session=sf.openSession(); //toString()
tx=session.beginTransaction(); }
Customer stu=new 3. CIDGenerator.java
Customer("sri","[email protected]",99999); package com.coursecube.hibernate;
session.save(stu);
tx.commit(); import java.io.*;
session.close(); import org.hibernate.*;
}catch(Exception ex) { import org.hibernate.engine.spi.*;
ex.printStackTrace(); import org.hibernate.id.IdentifierGenerator;
if(tx!=null) public class CIDGenerator implements IdentifierGenerator{
tx.rollback(); @Override
}}} public Serializable
2. Customer.java generate(SharedSessionContractImplementor sessionImpl,
package com.coursecube.hibernate; Object obj) throws HibernateException {
System.out.println("CIDGenerator-generate()");
import javax.persistence.*; String cid="C-001";
import org.hibernate.annotations.GenericGenerator; try {
Session session=(Session)sessionImpl;
@Entity String HQL="select max(cust.cid) from Customer cust";
@Table(name="mycustomers") String
public class Customer { id=session.createQuery(HQL,String.class).uniqueResult();
if(id!=null) {
@Id int x=Integer.parseInt(id.substring(2));
@GeneratedValue(generator = "cid_generator") x=x+1;
@GenericGenerator(name = "cid_generator",strategy = if(x<=9)
"com.coursecube.hibernate.CIDGenerator") cid="C-00"+x;
@Column(name="cid") else if(x<=99)
private String cid; cid="C-0"+x;
else if(x<=999)
@Column(name="cname") cid="C-"+x;
private String cname; }
}catch(Exception ex) { ex.printStackTrace(); }
@Column(name="email") return cid;
private String email; } }

Java Learning Center 136 Hibernate5 Study Guide


Composite Primary Key:
 When you specify the Primary key for combination of two or more Columns then it is
called as Composite Primary Key.

 Composite Primary Key can be configured in two ways.


1)@IdClass annotation (Refer Lab30)
2)@Embeddable and @Embedded annotations (Refer Lab31)

 When ever you have the requirement of Composite Primary key, then you must write
Custom Composite Primary Key class with the following steps.

Step 1: Write a Custom Composite Primary Key class by implementing Serializable.


Step 2: Declare the Fields related to Composite Primary Key columns.
Step 3: Write Constrcutors
Step 4: Write Setters and Gettters
Step 5: Override toString() method.
Step 6: Override equals() method.
Step 7: Override hashCode() method.

 Hibernate does not Provide any Built-In ID Generators for Composite Primary keys,
you have to write your own Custom ID Generators.

Generating value for Composite Primary Key:


Refer Lab32:

Java Learning Center 137 Hibernate5 Study Guide


Lab30: Using Composite Primary Key
Lab30: Files required
1. Lab30A.java 2. Lab30B.java
3. Account.java 4. AccountNumber.java
5. HibernateUtil.java

1. Lab30A.java 2. Lab30B.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

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 Lab30B {
public class Lab30A { public static void main(String[] args) {
public static void main(String[] args) { Transaction tx=null;
Transaction tx=null; try {
try { SessionFactory sf=HibernateUtil.getSessionFactory();
SessionFactory sf=HibernateUtil.getSessionFactory(); Session session=sf.openSession();
Session session=sf.openSession(); tx=session.beginTransaction();
tx=session.beginTransaction();
AccountNumber accNO=new
Account acc=new Account(99,"02",55555,new AccountNumber(99,"02",55555);
Date(),500000,"Active");
Account acc=session.load(Account.class, accNO);
session.save(acc); System.out.println(acc);

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 138 Hibernate5 Study Guide


3. Account.java //Setters and Getters
package com.coursecube.hibernate;
@Override
import java.util.Date; public String toString() {
import javax.persistence.*; return branchCode + "\t" + accType + "\t" + accId + "\t" +
/* accOpenDate + "\t" + balance + "\t" + status;
* @Author : Srinivas Dande }
* @company : Java Learning Center }
* */ 4. AccountNumber.java
@Entity package com.coursecube.hibernate;
@Table(name="myaccounts")
@IdClass(AccountNumber.class) import java.io.*;
public class Account { /*
@Id * @Author : Srinivas Dande
@Column(name="branchCode") * @company : Java Learning Center
private int branchCode; * */
@Id public class AccountNumber implements Serializable{
@Column(name="accType") private int branchCode;
private String accType ; private String accType ;
private int accId;
@Id
@Column(name="accId") public AccountNumber() {}
private int accId;
public AccountNumber(int branchCode, String accType, int
@Column(name="accOpenDate") accId) {
private Date accOpenDate; super();
this.branchCode = branchCode;
@Column(name="balance") this.accType = accType;
private double balance; this.accId = accId;
}
@Column(name="status")
private String status; //Setters and Getters

public Account() { } }

public Account(int branchCode, String accType, int


accId, Date accOpenDate, double balance, String
status) {
super();
this.branchCode = branchCode;
this.accType = accType;
this.accId = accId;
this.accOpenDate = accOpenDate;
this.balance = balance;
this.status = status;
}

Java Learning Center 139 Hibernate5 Study Guide


Lab31: Using Composite Primary Key
Lab31: Files required
1. Lab31A.java ( 2. Lab31B.java
3. Account.java 4. AccountNumber.java
5. HibernateUtil.java

1. Lab31A.java 2. Lab31B.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

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 Lab31A { public class Lab31B {
public static void main(String[] args) { public static void main(String[] args) {
Transaction tx=null; Transaction tx=null;
try { try {
SessionFactory sf=HibernateUtil.getSessionFactory(); SessionFactory sf=HibernateUtil.getSessionFactory();
Session session=sf.openSession(); Session session=sf.openSession();
tx=session.beginTransaction(); tx=session.beginTransaction();
AccountNumber accNO=new
AccountNumber(95,"02",55555); AccountNumber accNO=new
AccountNumber(95,"02",55555);
Account acc=new Account(accNO,new Account acc=session.load(Account.class, accNO);
Date(),75000,"Active"); System.out.println(acc);
session.save(acc);
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 140 Hibernate5 Study Guide


3. Account.java 4. AccountNumber.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

import java.util.Date; import java.io.*;


import javax.persistence.*;
import javax.persistence.*; /*
@Entity * @Author : Srinivas Dande
@Table(name="myaccounts") * @company : Java Learning Center
public class Account { * */
@Id
@Embedded @Embeddable
private AccountNumber accNumber; public class AccountNumber implements Serializable{
private int branchCode;
@Column(name="accOpenDate") private String accType ;
private Date accOpenDate; private int accId;

@Column(name="balance") public AccountNumber() {}


private double balance; public AccountNumber(int branchCode, String accType, int
accId) {
@Column(name="status") super();
private String status; this.branchCode = branchCode;
this.accType = accType;
public Account() { } this.accId = accId;
}
public Account(AccountNumber accNumber, Date
accOpenDate, double balance, String status) { //Setters and Getters
super();
this.accNumber = accNumber; @Override
this.accOpenDate = accOpenDate; public String toString() {
this.balance = balance; return branchCode + "\t" + accType + "\t" + accId ;
this.status = status; }
} }

//Setters and Getters

@Override
public String toString() {
return accNumber.toString() + "\t" + accOpenDate +
"\t" + balance + "\t" + status;
}

Java Learning Center 141 Hibernate5 Study Guide


Lab32: Using Custom Generation for Composite Primary Key
Lab32: Files required
1. Lab32A.java ( 2. Lab31B.java
3. Account.java 4. AccountNumber.java
5. HibernateUtil.java

1. Lab32A.java 2. Lab32B.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

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


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

StudentID stuId= new StudentID(101,"B25"); StudentID


Student stu=new stuId1=(StudentID)SIDGenerator.getNextStudentId(session,
Student(stuId,"sd","[email protected]",99999); "B26");
session.save(stu); Student stu1=new Student(stuId1,"sd","[email protected]",99999);
tx.commit(); session.save(stu1);
session.close();
StudentID
Session session=sf.openSession(); stuId2=(StudentID)SIDGenerator.getNextStudentId(session,
tx=session.beginTransaction(); "B25");
Student stu2=new Student(stuId2,"ds","[email protected]",99999);
StudentID stuId= new StudentID(101,"B25"); session.save(stu2);
Student stu=session.load(Student.class, stuId);
System.out.println(stu); tx.commit();
session.close();
tx.commit();
session.close(); }catch(Exception ex) {
ex.printStackTrace();
}catch(Exception ex) { if(tx!=null)
ex.printStackTrace(); tx.rollback();
if(tx!=null) }
tx.rollback(); }
} }
}
}

Java Learning Center 142 Hibernate5 Study Guide


3. Student.java 4. StudentID.java
package com.coursecube.hibernate; package com.coursecube.hibernate;

import javax.persistence.*; import java.io.*;


/* import javax.persistence.*;
* @Author : Srinivas Dande @Embeddable
* @company : Java Learning Center public class StudentID implements Serializable {
* */ private int sid;
private String bid;
@Entity public StudentID() {}
@Table(name="mystudents") public StudentID(int sid, String bid) {
public class Student { this.sid = sid;
@Id this.bid = bid;
@Embedded }
private StudentID stuId; //Setters and Getters
@Override
@Column(name="sname") public String toString() {
private String sname; return sid + "\t" + bid;
}
@Column(name="email") }
private String email; 5. SIDGenerator.java
package com.coursecube.hibernate;
@Column(name="phone")
private long phone; import java.io.*;
import org.hibernate.*;
public Student() { }
public class SIDGenerator{
public Student(StudentID stuId, String sname, String public static Serializable getNextStudentId(Session
email, long phone) { session,String bid) {
super(); StudentID stuId=null;
this.stuId = stuId; try {
this.sname = sname; String HQL="select max(stu.stuId.sid) from Student stu where
this.email = email; stu.stuId.bid=?1";
this.phone = phone; Integer
} sid=session.createQuery(HQL,Integer.class).setParameter(1,bi
//Setters and Getters d).uniqueResult();
@Override if(sid==null) {
public String toString() { stuId=new StudentID(101,bid);
return stuId.toString()+ "\t"+sname+"\t" + }else {
email + "\t" + phone; sid=sid+1;
} stuId=new StudentID(sid,bid);
}
} }catch(Exception ex) {
ex.printStackTrace();
}
return stuId;
}
}

Java Learning Center 143 Hibernate5 Study Guide


Hibernate Connection Management
 ConnectionProvider is an interface which has the following concrete
implementations.
1) DriverManagerConnectionProvider
2) C3P0ConnectionProvider
3) DatasourceConnectionProvider
 If these built-in ConnectionProviders are not suitable for your requirement, you can
write your own ConnectionProvider class by implementing
org.hibernate.connection.ConnectionProvider interface.
 You can specify the Custom ConnectionProvider in hibernate.cfg.xml as follows.
<property name="hibernate.connection.provider_class">
com.jlcindia.connection.JLCConnectionProvider
</property>

Built-in ConnectionProvider
A) DriverManager Connections
B) C3P0 Connections
C) DataSource Connections

A) DriverManager connections
 You need to specify the following properties in Hibernate configuration document.

For MySQL database


<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/jlcindiadb</property>
<property name="connection.username">root</property>
<property name="connection.password">srinivas</property>
<property name="connection.pool_size">99</property>
For Oracle database
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">srinivas</property>
<property name="connection.pool_size">99</property>

B) C3P0 Connections
 C3P0 is Third-Party Connection pooling technique which can be used in any kind of
Application.
 When you want to use C3P0 Connections, do the following.
o Add c3p0-0.9.1.jar to project build path.
o You need to specify the following properties in Hibernate configuration
document.

Java Learning Center 144 Hibernate5 Study Guide


For MySQL database
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/jlcindiadb</property>
<property name="connection.username">root</property>
<property name="connection.password">srinivas</property>
<property name="hibernate.c3p0.max_size">99</property>
<property name="hibernate.c3p0.min_size">9</property>
<property name="hibernate.c3p0.timeout">10</property>
For Oracle database
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">srinivas</property>
<property name="hibernate.c3p0.max_size">99</property>
<property name="hibernate.c3p0.min_size">9</property>
<property name="hibernate.c3p0.timeout">10</property>

C) DataSource Connections
1) To Use DataSource Connections, Your Hibernate Application must run in CME
(Container Managed Environment).
2) You need to specify the following properties in Hibernate configuration document.

For Weblogic Application Server


<property name="connection.datasource">MySQLDataSource</property>
<property name="jndi.class">weblogic.jndi.WLInitialContextFactory</property>
<property name="jndi.url">t3://localhost:7001</property>
<property name="connection.username">jlcindia</property>
<property name="connection.password">jlcindia</property>

For JBoss Application Server


<property name="connection.datasource">MySQLDataSource</property>
<property name="jndi.class">org.jnp.interfaces.NamingContextFactory</property>
<property name="jndi.url">localhost:1099</property>
<property name="connection.username">jlcindia</property>
<property name="connection.password">jlcindia</property>

Java Learning Center 145 Hibernate5 Study Guide


Example using C3P0 Connection Pooling
Lab37: Files required
1. Lab37A.java 2. Lab37B.java
3. Customer.java 4. HibernateUtil.java

1. Lab37A.java
package com.coursecube.hibernate;

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

Transaction tx=session.beginTransaction();
Customer cust=new Customer("sri","[email protected]",12345,"Blore",20000);
session.save(cust);
tx.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
} } }

2. Lab37B.java
package com.coursecube.hibernate;

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

Transaction tx = session.beginTransaction();
Customer cust = session.load(Customer.class, 1);
System.out.println(cust);
tx.commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
} } }

Java Learning Center 146 Hibernate5 Study Guide


3.Customer.java
package com.coursecube.hibernate;

import javax.persistence.*;
import org.hibernate.annotations.CacheConcurrencyStrategy;
/*
* @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 long phone;

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

@Column(name = "balance")
private double balance;

//Constructors
//Setters and Getters
//toString()
}
4. HibernateUtil.java
package com.coursecube.hibernate;

import java.util.Properties;
import org.hibernate.*;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
/*
* @Author : Srinivas Dande
* @company : CourseCube
* @see : www.coursecube.com
* */
public class HibernateUtil {

Java Learning Center 147 Hibernate5 Study Guide


static SessionFactory sessionFactory =null;
static {
try {
Configuration cfg = new Configuration();
Properties myprops = new Properties();
myprops.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
myprops.put(Environment.URL, "jdbc:mysql://localhost:3306/hellodb");
myprops.put(Environment.USER, "root");
myprops.put(Environment.PASS, "srinivas");

myprops.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
myprops.put(Environment.SHOW_SQL, "true");
myprops.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
myprops.put(Environment.HBM2DDL_AUTO, "update");

myprops.put(Environment.C3P0_MIN_SIZE,10);
myprops.put(Environment.C3P0_MAX_SIZE,99);
myprops.put(Environment.C3P0_MAX_STATEMENTS,5);
myprops.put(Environment.C3P0_TIMEOUT,1);

cfg.setProperties(myprops);
cfg.addAnnotatedClass(Customer.class);

StandardServiceRegistryBuilder ssrbuilder= new StandardServiceRegistryBuilder();


ServiceRegistry serviceRegistry = ssrbuilder.applySettings(cfg.getProperties()).build();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);

} catch (Exception e) {
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Example using Hikari Connection Pooling


Lab38: Files required
1. Lab38A.java (Same as Lab37A) 2. Lab38B.java (Same as Lab37B)
3. Customer.java (Same as Lab37) 4. HibernateUtil.java

4. HibernateUtil.java
package com.coursecube.hibernate;

import java.util.Properties;
import org.hibernate.*;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
/*

Java Learning Center 148 Hibernate5 Study Guide


* @Author : Srinivas Dande
* @company : CourseCube
* @see : www.coursecube.com
* */
public class HibernateUtil {
static SessionFactory sessionFactory =null;
static {
try {
Configuration cfg = new Configuration();

Properties myprops = new Properties();


myprops.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
myprops.put(Environment.URL, "jdbc:mysql://localhost:3306/hellodb");
myprops.put(Environment.USER, "root");
myprops.put(Environment.PASS, "srinivas");

myprops.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
myprops.put(Environment.SHOW_SQL, "true");
myprops.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
myprops.put(Environment.HBM2DDL_AUTO, "update");

// Maximum waiting time for a connection from the pool


myprops.put("hibernate.hikari.connectionTimeout", "20000");

// Minimum number of ideal connections in the pool


myprops.put("hibernate.hikari.minimumIdle", "10");

// Maximum number of actual connection in the pool


myprops.put("hibernate.hikari.maximumPoolSize", "99");

// Maximum time that a connection is allowed to sit ideal in the pool


myprops.put("hibernate.hikari.idleTimeout", "300000");

cfg.setProperties(myprops);
cfg.addAnnotatedClass(Customer.class);

StandardServiceRegistryBuilder ssrbuilder= new StandardServiceRegistryBuilder();


ServiceRegistry serviceRegistry = ssrbuilder.applySettings(cfg.getProperties()).build();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);

} catch (Exception e) {
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Java Learning Center 149 Hibernate5 Study Guide

You might also like