Hibernate Training Session1

31
Hibernate Training Session 1 Prepared By Asad Khan

Transcript of Hibernate Training Session1

1. Prepared By Asad Khan 2. What is Hibernate means? Animals that sleep through the winter, like bears, squirrels, bat etc. Hibernation is characterized by low body temperature, slow breathing and heart rate, and low metabolic rate. 3. Can Human be Hibernate in Future? The extreme survival tricks of hibernating animals and the occasional human could help us overcome life-threatening injuries, as Frank Swain discovers. 4. In Java world Hibernate is a well- known ORM Framework What is an ORM? Object Relational Mapping (ORM) is a programming technique to access the data from source which is incompatible with object orientated paradigm. Why do we need ORM? Speeding development/Huge reduction in code. DBMS Compatibility Focus on Business more Make CRUD operation to behave OOP way Cache mechanism 5. Typical flow of an ORM ORM act as a bridge b/w Object oriented application and relational database. 6. Other ORMs? Is there any other ORMs? Eclipse Link Apache Cayenne Top Link Open JPA Then Why Hibernate? Popularity Performance Vast support/Help Reliable JPA 2.1 compliant Cache support 7. Comparison with JDBC Lets see their fight in eclipse IDE HIBERNATE JDBC 8. Lets Begin Hibernate 9. JPA Hibernate Architecture 10. Hibernate Core Classes Flow Read Configuration and setup hibernate Manage Session /Create Session Make group of dependent instruction to single Execute single instruction Execute HQL Act as a Where clause 11. Closer look of Hibernate and JPA Hibernate does more than JPA 12. What is JPA History There were no standard for ORM until JPA introduced. JPA 1.0 was born in 2006 (Java EE 5)/ Influenced by Hibernate. So What is it? JPA is a specification to standardize ORM-APIs or specification for accessing, persisting and managing the data between Java objects and the relational database. It means it went through the Java Community Process. Its specification # is JSR338 (https://jcp.org/en/jsr/detail?id=338) Following are implementation of JPA: 1)Eclipse Link 2) Hibernate 3)Open JPA These are interchangeable or no vendor locking. 13. Hibernate Setup We will be using Hibernate version 4.3.7 in this training and you can get from below link: http://hibernate.org/orm/downloads Hibernate JBOSS Tool for Eclipse: http://download.jboss.org/jbosstools/updates/stable/lu na/ 14. Basic Setup for Hibernate 1. Create Java SE/EE Project. 2. Create Hibernate configuration file. Note: more about this configuration file in next slide 3. Create Java Bean/ Class (Persistent Class).Note: more about this class in next slide 4. Create Mapping File of that Class. 5. Map this class in Hibernate Configuration file. 15. Hibernate Configuration Properties hibernate.use_sql_comments: true /false (true means show, false means dont) hibernate.format_sql: Pretty print the SQL in the log and console. e.g. true | false hibernate.dialect: The classname of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular relational database.e.g. full.classname.of.Dialect hibernate.show_sql: Write all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug. e.g. true | false hibernate.default_schema: Qualify unqualified table names with the given schema/tablespace in generated SQL. e.g. SCHEMA_NAME hibernate.hbm2ddl.auto: Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly. e.g. validate | update | create | create-drop 16. Following rules must be followed when declaring Persistent Class The four main rules of persistent classes : Implement a no-argument constructor Provide an identifier property (optional) Prefer non-final classes (optional) Declare accessors and mutators for persistent fields (optional) See the Employee class example in code. 17. Mapping Data Types 18. Types of Generator in Hibernate Assigned: lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified. Identity: supports identity columns in DB2, MySQL, MS SQL Server, Sybase and Hypersonic SQL. The returned identifier is of type long, short or int. Sequence: uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int. Uuid: uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length. Increment: generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. There are many more classes for generator. Please visit the following site: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html 19. What is an Entity Entity : An entity is something that exists in itself, actually or potentially, concretely or abstractly, physically or not physically (conceptually). 20. Attribute A property, or a conclusion of a characteristic of an entity or substance or An attribute is a characteristic of an entity. 21. Entity type or Value(Attribute) type Any piece of data can be expressed as entity type or value type: Entity Types: Entities have a unique identity means exist independently and define their own lifecycle., which stays the same despite of changes in the properties of the object. For example Human, mobile, computer etc. 22. Value Types A value type do not define their own lifecycle. We say that they are "owned" by something else (specifically an entity) which defines their lifecycle. For Example: name, address, age of Employee, hand of human, nip of a pen, wheel of a car, companies history of an employee etc. Value types are further classified into 3 sub-categories: basic types, composite types and collection types. Basic Types: age, name, sex of an employee in single value. Composite types: aggregate values of basic types for i.e. address of employee contain (country , state ,city and street). Collection types: collection of data for i.e. companies history of an employee, daily activities of an employee. 23. Composite Value Type and its mapping with an Entity Address as a composite value type of an employee. Lets see the example of mapping with an entity in code. Collection Value Type and its mapping with an Entity In hibernate always declare a collection variable type by their parent interface. For example Set, List, Map, Collection etc. Because when we get back the collection object from hibernate its type will be change by hibernate. It wont be the Java HashSet or ArrayList or HashMap, Its type will be in specialized form. 24. Uni-directional and Bi-directional relationship Uni-directional Bi-directional Recommended approach make relationship bidirectional in class. 25. Collection Value Type as HashSet Example HashSet Properties: A Set represents a mathematical set. It is a Collection that, unlike List, does not allow duplicates. There must not be two elements of a Set, say e1 and e2, such that e1.equals(e2). The add method of Set returns false if you try to add a duplicate element. HashSet allows at most one null element. HashSet is faster than other implementations of Set, TreeSet and LinkedHashSet. Lets see in action the Employee Activities as a collection value type of an employee using HashSet in a program. 26. Collection Value Type as ArrayList Example An ArrayList is an ordered collection Permits null elements It is not synchronized Lets see in action the Past Companies as a collection value type of an employee using ArrayList in a program. 27. Collection Value Type as HashMap Example No guarantees as to the order of the map. Uniqueness guarantee. No guarantee that the order will remain constant. It is unsynchronized and permits nulls. Lets see HashMap collection value type in an action using Employee Roles in a program. 28. What's Next Next we will do Entity relationship. One-to-one One-to-many Many-to-one 29. See You Next Time