hiberanate using jpa annotations

15
Hibernate : Using Java JPA Annotations. Connectivity of Hibernate and Database 1.hibernate.cfg.xml <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//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.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="myeclipse.connection.profile">MyHibernateDriver</property> <property name="show_sql">true</property> <property name="hibernate.current_session_context_class">thread</property> </session-factory> </hibernate-configuration> List of Jar Files: Hibernat Databas e

Upload: avishekh-sinha

Post on 15-Oct-2014

53 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Hiberanate Using JPA Annotations

Hibernate : Using Java JPA Annotations.

Connectivity of Hibernate and Database1.hibernate.cfg.xml<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//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.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="myeclipse.connection.profile">MyHibernateDriver</property> <property name="show_sql">true</property> <property name="hibernate.current_session_context_class">thread</property> </session-factory></hibernate-configuration>

List of Jar Files:

HibernateDatabase

Page 2: Hiberanate Using JPA Annotations

List of Dialect in different database1. DB2 - org.hibernate.dialect.DB2Dialect2. HypersonicSQL - org.hibernate.dialect.HSQLDialect3. Informix - org.hibernate.dialect.InformixDialect4. Ingres - org.hibernate.dialect.IngresDialect5. Interbase - org.hibernate.dialect.InterbaseDialect6. Pointbase - org.hibernate.dialect.PointbaseDialect7. PostgreSQL - org.hibernate.dialect.PostgreSQLDialect8. Mckoi SQL - org.hibernate.dialect.MckoiDialect9. Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect10. MySQL - org.hibernate.dialect.MySQLDialect11. Oracle (any version) - org.hibernate.dialect.OracleDialect12. Oracle 9 - org.hibernate.dialect.Oracle9Dialect13. Progress - org.hibernate.dialect.ProgressDialect14. FrontBase - org.hibernate.dialect.FrontbaseDialect15. SAP DB - org.hibernate.dialect.SAPDBDialect16. Sybase - org.hibernate.dialect.SybaseDialect17. Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect

Note: use javax.persistance.*

@Entity @Table(name = "EmployeeInfo")public class Employee {

@Id@TableGenerator(name = "empid", table = "emppktb", pkColumnName = "empkey", pkColumnValue = "empvalue", allocationSize = 1)@GeneratedValue(strategy = GenerationType.TABLE, generator = "empid")@Column(name = "employeeid")private int empID;private String empName;@Transientprivate String empPassword;@Column(nullable = false)private String empEmailAddress;@Basicprivate boolean isPermanent;@Temporal(TemporalType.DATE)private Calendar empJoinDate;@Temporal(TemporalType.TIMESTAMP)private Date empLoginTime;// getter and setters}

Details of Annotations : -@Entity – It Tells Hibernate to create a table in the database same as the name of the class and the properties of the class as it columns. For Example,

@Entity public class Employee {..}

@Entity @Table(name = "EmployeeInfo")public class Employee { .. }By Default the table is same as the class name ,But the table name can be customized and can be user defined by using @Table annotation .For example, the above code create a table having name EmployeeInfo 1. @Id – This Annotation is applied on the property of a classes .It denotes that the property on which it is

applied is going to be the primary Key of the table being created

Page 3: Hiberanate Using JPA Annotations

2. @Generated Value- This Annotation tells the primary key is auto generated by Hibernate Itself .3. @GeneratedValue(strategy = GenerationType.TABLE, generator = "empid") – To maintain a desired

sequence in the primary Types of strategy(GenerationType)

AUTO( default):- It ensures that the primary key will be unique IDENTITY – same as AUTO SEQUENCE – Generates the primary key as per the sequence (if the database supports Sequence,

like Oracle) TABLE – It maintains the primary key with the help of a table.Below two Annotation will be used

for GenerationType TABLE. Its creates a table which maintains the next sequence to be generated. The details of the table created is Mentioned below when the following configation.

@TableGenerator(name = "empid", table = "emppktb", pkColumnName = "empkey", pkColumnValue = "empvalue", allocationSize = 1)@GeneratedValue(strategy = GenerationType.TABLE, generator = "empid")

TableName= emppktb [table = "emppktb"]empkey(pkColumnName) SEQUENCE_NEXT_HI_VALUEempvalue(pkColumnValue) 6

4. @Column(name=”name_of_user_defined_column) - By Default the table column name is same as the property name ,But the column name can be customized and can be user defined by using @ Column annotation .For example, the below code create a column in EmployeeInfo having name employeeidb) @Column(nullable = false) – It makes the column NOT NULL.For Example,@Entity @Table(name = "EmployeeInfo")public class Employee {

@GeneratedValue@Column(name = "employeeid") @Column(nullable = false)private String empEmailAddress;

5. @Transient - This Annotation is applied on the property of a classes. The columns created in the table is as per the property of the @Entity class with the same name as of properties ,but @Transient tells hibernate not to create the column corresponding to the property of class marked @Transient .For Example,@Entity @Table(name = "EmployeeInfo")public class Employee {

private String empName;@Transientprivate String empPassword;

}It creates a table EmployeeInfo having only one column – empName, but ignores empPassword because it is marked @Transient

6. @Temporal – If we want to store The Date/Time/TimeStamp in the DB the we use @Temporal AnnotationFor Example@Temporal(TemporalType.DATE)private Calendar empJoinDate;@Temporal(TemporalType.TIMESTAMP)private Date empLoginTime;

Page 4: Hiberanate Using JPA Annotations

Testing The Employee Class :- public class TestEmployee {public static void main(String[] args) {

AnnotationConfiguration configuration = new AnnotationConfiguration();configuration.addAnnotatedClass(Employee.class); //Tells which class is Annotated with @Entityconfiguration.configure("hibernate.cfg.xml"); //Read the configuration filenew SchemaExport(configuration).create(true, true);//Above function creates a table ( and drops if already present).SessionFactory factory = configuration.buildSessionFactory();Session session = factory.getCurrentSession();session.beginTransaction();// employee.setEmpID("300");{Employee employee1 = new Employee();employee1.setEmpName("Linda");employee1.setEmpEmailAddress("[email protected]");employee1.setEmpJoinDate(new GregorianCalendar(2009, 12, 12));employee1.setEmpLoginTime(Date.valueOf("2010-02-02"));// till here the employee1 object is transientsession.save(employee1); // here employee1 object is persistent}{Employee employee2 = new Employee();employee2.setEmpName("WWW Smith");employee2.setEmpEmailAddress("[email protected]");employee2.setEmpJoinDate(new GregorianCalendar(2009, 12, 12));employee2.setEmpLoginTime(Date.valueOf("2010-02-02"));session.save(employee2);}session.getTransaction().commit();}}

create(true,true)= create method has two Boolean argument a) First “true ” tells hibernate to print the sql statement in logsb) Second “true” tells hibernate to execute the queries in the database.

2. Create Two table from One Java Class@Entity@Table(name = "Customer")@SecondaryTable(name = "CustomerDetail")public class Customer {

@Id@GeneratedValueprivate int customerId; // This column will be created in customer Tableprivate String customerName; // This column will be created in customer Table@Column(table = "CustomerDetail") private String customerAddress; // This column will be created in customerDetails Table@Column(table = "CustomerDetail")private int creditScore; // This column will be created in customerDetails Table@Column(table = "CustomerDetail")private int rewardPoints; // This column will be created in customerDetails Table//getters and setters}

Details:-

Page 5: Hiberanate Using JPA Annotations

Note: - This Piece of code creates two table having name Customer and Customerdetail with below structure and maintains reference integrity also.

1. @SecondaryTable(name = "CustomerDetail") -It Creates the Secondary Table having name Customerdetail

Table Name: CustomercustomerId(Auto generated)

customerName

Customer :-

Customerdetail :-

Testing the Customer Class:-public class TestCustomer {

public static void main(String[] args) {//same code as beforeCustomer customer=new Customer();customer.setCustomerName("Alex");customer.setCreditScore(233);customer.setRewardPoints(342);customer.setCustomerAddress("India");session.save(customer);session.getTransaction().commit();

}}2. Create one table from Two Classes :-

Note: Only one class is Annotated with @Entity (here School Class is Annotated),otherwise it would have created two different table corresponding to each class

@Entitypublic class School {

@Id@GeneratedValueprivate int schoolID;private String schoolName;@Embeddedprivate SchoolDetail schoolDetail;//getter and setters}

@Embeddablepublic class SchoolDetail {

private String schoolAddress;private boolean isSchoolPublic;private int studentCount;//getter and setters}

Testing the School classpublic class TestSchool {

public static void main(String[] args) {//same code as before

Table Name: CustomerDetailscustomerAddress

creditScorerewardPoints

customerId(Auto generated)

Page 6: Hiberanate Using JPA Annotations

SchoolDetail schoolDetail=new SchoolDetail();schoolDetail.setSchoolAddress("101 Washington dc");schoolDetail.setSchoolPublic(false);schoolDetail.setStudentCount(300);School school=new School();school.setSchoolDetail(schoolDetail);school.setSchoolName("St. Anns School");session.save(school);session.getTransaction().commit();

}}Table Name: School

3. Compound Primary Key :- This Configuration create the Unique Combination of Primary Key

@Entitypublic class Accounts {

@Idprivate CompoundKey compoundKey;private int accountBalance;//getter and setters }

import java.io.Serializable;import javax.persistence.Embeddable;@Embeddablepublic class CompoundKey implements Serializable{ // it is mandatory that the compound key should implement Serializable Interface

private int userId;private int accountId;public CompoundKey(int userId, int accountId) {

super();this.userId = userId;this.accountId = accountId;}

//getter and setters}Testing the Accounts Classpublic class TestAccount {

public static void main(String[] args) {//same code as before

{CompoundKey compoundKey = new CompoundKey(100, 10001);Accounts accounts = new Accounts();accounts.setCompoundKey(compoundKey);accounts.setAccountBalance(3500);session.save(accounts);}

{CompoundKey compoundKey1 = new CompoundKey(100, 20001);Accounts accounts1 = new Accounts();accounts1.setCompoundKey(compoundKey1);accounts1.setAccountBalance(2500);session.save(accounts1);}session.getTransaction().commit();}}

Account table: Note the Unique combinations of ACCOUNTID and USERID

Page 7: Hiberanate Using JPA Annotations

Inheritance MappingInheritance Types (strategy)

SINGLE_TABLE(Default) JOINED TABLE_PER_CLASS

@Entity@Inheritance(strategy=InheritanceType.JOINED)public class Project {

@Id@GeneratedValueprivate int projectId;private String projectName;//getter and setters}

@Entitypublic class Module extends Project {

private String moduleName;//getter and setters}

@Entitypublic class Task extends Module {

private String taskName;//getter and setters}

Testing Inheritance Mappingpublic class TestInheritance {

public static void main(String[] args) {//same code as before

Project project=new Project();project.setProjectName("Hibernate Lesson");Module module=new Module();module.setProjectName("Spring Lesson");module.setModuleName("AOP");Task task=new Task();

task.setModuleName("Collections");task.setProjectName("Java Lessons");task.setTaskName("ArrayList");session.save(project);session.save(module);session.save(task);session.getTransaction().commit();}}

1. Case 1 : if @Inheritance(strategy=InheritanceType SINGLE_TABLE): It creates a Single Table corresponding to each properties of inherited Classes (Project Module Task)

2. Case 2 : if @Inheritance(strategy=InheritanceType.JOINED) :- It Creates three different table corresponding to each different classes and maintain the refrential integrity also

Table Name: Project (PROJECTID- Primary Key)

Table Name :Module(PROJECTID- Primary Key)

TableName:Task(PROJECTID- Primary Key)

Project

Module

Task

Page 8: Hiberanate Using JPA Annotations

3.Case 3: if @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) :- Here also three tables are created but in different manner Table Name: Project

Table Name :Module

TableName:Task

One To One Mapping

Note :- personalDetailId is the JoinColumn@Entitypublic class Person {

@Id@GeneratedValueprivate int personId;private String personName;

@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)@JoinColumn(name = "pDetails_FK")private PersonDetail personDetail;// create an Instance of Persondetail table.. It’s a Join Column//getter and setters

}@Entitypublic class PersonDetail {

@Id@GeneratedValue@Column(name="detailId_PK")private int personalDetailId;private String zipCode;private String job;private int income;//getter and setters

}One To One : BiDirectional :In Case of Bi-direction data fetching(Note that only Persondetail needs to be changed)

Join Column

Page 9: Hiberanate Using JPA Annotations

@Entitypublic class PersonDetail {

@Id@GeneratedValue@Column(name="detailId_PK")private int personalDetailId;private String zipCode;private String job;private int income;@OneToOne(mappedBy="personDetail",cascade=CascadeType.ALL)private Person person;//getter and setters

}Details of Annotations:Cascade Type :- It Ensures that the Child data is also get deleted from Child Table when the Parent data is deleted from the Parent table

ALL MERGE PERSIST REMOVE REFRESH

FetchType:- EAGER – if we want to load the data from Person Details to be loaded when Person record is loaded the

we have to use FetchType=EAGER LAZY - if we want to load the data from Person Details to be loaded if its required ,when Person record is

deleted the we have to use FetchType=LAZYTesting the Person Classpublic class TestPerson {

public static void main(String[] args) {//same code as beforePersonDetail personDetail=new PersonDetail();// its not savedpersonDetail.setIncome(100);personDetail.setJob("JOB");personDetail.setZipCode("1223");Person person=new Person();person.setPersonName("Alex");person.setPersonDetail(personDetail);session.save(person); //Only Person Object is persisted not the Persondetails pbjectsession.getTransaction().commit();

}}Note :- the saving of Persondetails object is not required and it maintains the referential integrity because @OneToOne(cascade = CascadeType.ALL) is already being doneOne to Many :- College can have many Student@Entitypublic class College {

@Id@GeneratedValueprivate int collegeId;private String collegeName;@OneToMany(targetEntity = Student.class, mappedBy = "college", cascade = CascadeType.ALL, fetch =

FetchType.LAZY) //Default fetch type is LAZYprivate List<Student> students;

Page 10: Hiberanate Using JPA Annotations

//getters and setters}@Entitypublic class Student {

@Id@GeneratedValueprivate int studentId;private String studentName;@ManyToOne@JoinColumn(name="collegeid")private College college;//getters and setters

}Annotation Details:-@OneToMany(targetEntity = Student.class, mappedBy = "college", cascade = CascadeType.ALL, fetch = FetchType.LAZY)a)targetEntity – This specifies the class name with which there is One to Many Relationship(here Student class)

College OneToManyStudent ; Student ManyToOneCollege; Testing the Student Classpublic class TestStudent {public static void main(String[] args) {//same code as beforeCollege college = new College();college.setCollegeName("New York College");Student student = new Student();Student student2 = new Student();student.setStudentName("Alex Rod");

student2.setStudentName("Linda");student.setCollege(college);student2.setCollege(college);session.save(college);session.save(student);session.save(student2);session.getTransaction().commit();}

}Generated TableTABLE NAME : College

TABLE NAME: Student

Many Two Many

@Entitypublic class Delegate {

Page 11: Hiberanate Using JPA Annotations

@Id@GeneratedValueprivate int delegateId;private String delegateName;@ManyToMany@JoinTable(name="JOIN_DELEGATE_EVENT",joinColumns={@JoinColumn(name="delegateId")},inverseJoinColumns={@JoinColumn(name="eventId")})private List<Event> events = new ArrayList<Event>();

//getters and setters}@Entitypublic class Event {

@Id@GeneratedValueprivate int eventId;private String eventName;@ManyToMany@JoinTable(name="JOIN_DELEGATE_EVENT",joinColumns={@JoinColumn(name="eventId")},inverseJoinColumns={@JoinColumn(name="delegateId")})private List<Delegate> delegates=new ArrayList<Delegate>();

//getters and setters}Testing the Event Classpublic class TestEvent {

public static void main(String[] args) {//same code as before

Delegate delegate1 = new Delegate();Delegate delegate2 = new Delegate();Delegate delegate3 = new Delegate();delegate1.setDelegateName("AAA");delegate2.setDelegateName("BBB");delegate3.setDelegateName("CCC");Event event1 = new Event();Event event2 = new Event();event1.setEventName("Java Event");

event2.setEventName("cplus event");event1.getDelegates().add(delegate1);event1.getDelegates().add(delegate2);event1.getDelegates().add(delegate3);event2.getDelegates().add(delegate2);event2.getDelegates().add(delegate3);session.save(delegate1);session.save(delegate2);session.save(delegate3);session.save(event1);session.save(event2);session.getTransaction().commit();

Eclipse Generated HibernateSessionFactoty classpackage com;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;public class HibernateSessionFactory {

private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION;

static { try {

configuration.configure(configFile);sessionFactory = configuration.buildSessionFactory();

} catch (Exception e) {System.err.println("%%%% Error Creating SessionFactory %%%%");

Page 12: Hiberanate Using JPA Annotations

e.printStackTrace();}

} private HibernateSessionFactory() { }

public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen()) {if (sessionFactory == null) {

rebuildSessionFactory();}session = (sessionFactory != null) ? sessionFactory.openSession(): null;threadLocal.set(session);

} return session; }

public static void rebuildSessionFactory() {try {

configuration.configure(configFile);sessionFactory = configuration.buildSessionFactory();

} catch (Exception e) {System.err.println("%%%% Error Creating SessionFactory %%%%");e.printStackTrace();

}}

public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } }

public static org.hibernate.SessionFactory getSessionFactory() {return sessionFactory;

}

public static void setConfigFile(String configFile) {HibernateSessionFactory.configFile = configFile;sessionFactory = null;

}public static Configuration getConfiguration() {

return configuration;}

}