Module 6 - Primary Keys and Connection Management (1)
Module 6 - Primary Keys and Connection Management (1)
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.
class Customer{
@Id
int cid;
}
Developer or Hibernate System or DB engine are Responsible for provding values
for Primary key filed.
Refer Lab21:
Refer Lab22:
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;
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;
...
}
We are specifying different tables for holding the Primar keys of Students and
Customers by using @SequenceGenerator.
Refer Lab25
@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;
...
}
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
@Id
@GeneratedValue(generator = "cid_generator")
@GenericGenerator(name = "cid_generator",strategy =
"org.hibernate.id.UUIDHexGenerator")
@Column(name="cid")
private String cid;
…
}
Refer Lab27
Client Code
String cid=(String)CIDGenerator.getNextCustomerId();
Customer cust=new Customer(cid,"sri","[email protected]",12345);
session.save(cust);
Refer Lab28
Refer Lab29
1. Lab21.java 2. Customer.java
package com.coursecube.hibernate; package com.coursecube.hibernate;
@Override
public String toString() {
return cid + "\t" + cname + "\t" + email + "\t" + phone ;
}
}
1. Lab22.java 2. Customer.java
package com.coursecube.hibernate; package com.coursecube.hibernate;
tx.commit(); @Column(name="email")
session.close(); private String email;
@Override
public String toString() {
return cid + "\t" + cname + "\t" + email + "\t" + phone ;
}
}
1. Lab23.java 2. Customer.java
package com.coursecube.hibernate; package com.coursecube.hibernate;
tx.commit(); @Column(name="email")
session.close(); private String email;
@Override
public String toString() {
return cid + "\t" + cname + "\t" + email + "\t" + phone ;
}
}
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();
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);
1. Lab25.java @Column(name="cname")
package com.coursecube.hibernate; private String cname;
@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
}
1. Lab26.java @Column(name="cname")
package com.coursecube.hibernate; private String cname;
1. Lab27.java 2. Customer.java
package com.coursecube.hibernate; package com.coursecube.hibernate;
tx.commit(); @Column(name="cname")
session.close(); private String cname;
} 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 ;
}
}
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; } }
When ever you have the requirement of Composite Primary key, then you must write
Custom Composite Primary Key class with the following steps.
Hibernate does not Provide any Built-In ID Generators for Composite Primary keys,
you have to write your own Custom ID Generators.
1. Lab30A.java 2. Lab30B.java
package com.coursecube.hibernate; package com.coursecube.hibernate;
tx.commit(); tx.commit();
session.close(); session.close();
public Account() { } }
1. Lab31A.java 2. Lab31B.java
package com.coursecube.hibernate; package com.coursecube.hibernate;
@Override
public String toString() {
return accNumber.toString() + "\t" + accOpenDate +
"\t" + balance + "\t" + status;
}
1. Lab32A.java 2. Lab32B.java
package com.coursecube.hibernate; package com.coursecube.hibernate;
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.
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.
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.
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();
} } }
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 {
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);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
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;
/*
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");
cfg.setProperties(myprops);
cfg.addAnnotatedClass(Customer.class);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}