Hibernate Concepts Students[1] Krsna-t-cube

download Hibernate Concepts Students[1] Krsna-t-cube

of 28

Transcript of Hibernate Concepts Students[1] Krsna-t-cube

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    1/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 1 of 28

    What is ORM? ................................................................................................................1

    Hibernate Types .........................................................................................................8

    Important Mappings .....................................................................................................9

    Collection Mapping ......................................................................................................14

    Associations ..............................................................................................................15

    Inheritance mapping Strategies .................................................................................21Hibernate Query Language ......................................................................................23

    Criteria Query ...............................................................................................................27

    SecondLevel cache ...................................................................................................28

    What is ORM?

    object/relational mapping is the automated persistence of objects in a Javaapplication to the tables in a relational database, using metadata thatdescribes the mapping between the objects and the database. ORM worksby transforming data from object representation to relational representation inRDBMS.

    The mapping of objects to the tables in the database is specified inhbm.xml files. An ORM solution provides

    1. An API for performing basic CRUD operations on objects of persistentclasses.

    2. An API for writing queries that refer to classes and properties ofclasses

    3. A means to specify mapping metadata

    Advantages of Hibernate/ORM

    Productivity : Java developers spend most of their on writing jdbc coderather than on application logic. Since, Hibernate takes most of theresponsibility of the persistence code, java developer can focus more on thebusiness problem.

    Maintainability : Since, most of the code related to persistence is generatedby ORM at the run time, it reduces the size of the code. Small code base iseasy to maintain and refactor.

    Performance: Hibernate comes with many optimizations to the persistence

    code. A developer, instead of fine tuning the performance by hand, can usethe optimizations provided by Hibernate.

    Database independence : Irrespective of the different types of databasesthat are there, hibernate provides a much easier way to develop a crossplatform application.

    Optimistic Transactions : Hibernate provides out-of-box support foroptimistic transaction for long running transactions.

    Caching : Hibernate provides elegant solutions for data caching. Caching the

    read-only data gives significant perfromance boost for the application.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    2/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 2 of 28

    Hibernate Architecture

    Hibernate Configuration File:

    Hibernate environment can be configured in a couple of ways. One standard way that

    proves very flexible and convenient is to store the configuration in a file named

    hibernate.cfg.xml. This configuration file is placed in the classpath of the application.Hibernate.cfg.xml file can be accessed and read using the

    org.hibernate.cfg.Configuration class at runtime.

    The hibernate.cfg.xml file defines information about the database connection, the

    transaction factory class, resource mappings, etc.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    3/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 3 of 28

    com.mysql.jdbc.Driverjdbc:mysql://localhost:3306/hibernateroot

    org.hibernate.dialect.MySQLDialectupdatethreadtrue

    Programming : With hibernate.cfg.xml starting hibernate is easy.Assuming the cfg.xml file is in class path,

    SessionFactory sf = new Configuration().configure().buildSessionFactory();

    Configuration file which has different name can be picked usingSessionFactory sf = new

    Configuration().configure(krsnatcube.cfg.xml).buildSessionFactory();

    The Hibernate Mapping Configuration File

    Hibernate applications make use of mapping files containing metadatadefining object/relational mappings for Java classes. A mapping file isdesignated with a suffix of .hbm.xml. Within each configuration file, classes tobe made persistent are mapped to database tables and properties are definedwhich map class-fields to columns and primary keys.

    The mapping document is designed to be readable and hand-editable. Themapping language is Java-centric, meaning that mappings are constructedaround persistent class declarations, not table declarations.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    4/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 4 of 28

    A number of tools exist to generate the mapping document, including XDoclet,Middlegen and AndroMDA.

    Lets discuss the various elements of the hibernate-mapping file

    schema (optional): The name of a database schema.default-cascade (optional - defaults to none): A default cascade style.default-access (optional - defaults to property): The strategy Hibernateshould use for accessing all properties.

    default-lazy (optional - defaults to true): The default value for unspecifed lazyattributes of class and collection mappings.package (optional): Specifies a package prefix to assume for unqualifiedclass names in the mapping document.

    name (optional): The fully qualified Java class name of the persistent class (orinterface). If this attribute is missing, it is assumed that the mapping is for anon-POJO entity.table (optional - defaults to the unqualified class name): The name of itsdatabase table.dynamic-update (optional, defaults to false): Specifies that UPDATE SQL

    should be generated at runtime and contain only those columns whose valueshave changed.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    5/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 5 of 28

    dynamic-insert (optional, defaults to false): Specifies that INSERT SQLshould be generated at runtime and contain only the columns whose valuesare not null.batch-size (optional, defaults to 1) specify a "batch size" for fetchinginstances of this class by identifier.

    optimistic-lock (optional, defaults to version): Determines the optimisticlocking strategy.lazy (optional): Lazy fetching may be completely disabled by settinglazy="false".

    Id:Mapped classes mustdeclare the primary key column of the databasetable.The element defines the mapping from that property to the primarykey column.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    6/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 6 of 28

    employer_id_seq

    uuid

    uses a 128-bit UUID algorithm to generate identifiers of type string, uniquewithin a network (the IP address is used). The UUID is encoded as a string ofhexadecimal digits of length 32.

    guiduses a database-generated GUID string on MS SQL Server and MySQL.

    hilouses a hi/lo algorithm to efficiently generate identifiers of type long, short orint, given a table and column (by default hibernate_unique_key and next_hi

    respectively) as a source of hi values. The hi/lo algorithm generates identifiersthat are unique only for a particular database.

    hi_valuenext_value100

    nativepicks identity, sequence or hilo depending upon the capabilities of theunderlying database.

    assignedlets the application to assign an identifier to the object before save() is called.This is the default strategy if no element is specified.

    Property:

    name: the name of the property, with an initial lowercase letter

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    7/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 7 of 28

    column (optional - defaults to the property name): the name of the mappeddatabase table column. This may also be specified by nested element(s).type (optional): a name that indicates the Hibernate type.update, insert (optional - defaults to true) : specifies that the mapped

    columns should be included in SQL UPDATE and/or INSERT statementsunique (optional): Enable the DDL generation of a unique constraint for thecolumns. Also, allow this to be the target of a property-ref.not-null (optional): Enable the DDL generation of a nullability constraint forthe columns.optimistic-lock (optional - defaults to true): Specifies that updates to thisproperty do or do not require acquisition of the optimistic lock. In other words,determines if a version increment should occur when this property is dirty.

    Component :

    The term "component" refers to the object-oriented notion of composition. Acomponent has no individual identity, hence the persistent component classrequires no identifier property or identifier mapping. Its a simple POJO:Hibernate uses the term component for a user-defined class that is persistedto the same table as the owning entity.

    Hibernate object states

    Hibernate defines and supports the following object states:

    Transient- an object is transient if it has just been instantiated using thenew operator, and it is not associated with a Hibernate Session. It has nopersistent representation in the database and no identifier value has beenassigned. Transient instances will be destroyed by the garbage collector if theapplication doesn't hold a reference anymore. Use the Hibernate Session tomake an object persistent (and let Hibernate take care of the SQL statements

    that need to be executed for this transition).Persistent- a persistent instance has a representation in the databaseand an identifier value. It might just have been saved or loaded; however, it isstill in the scope of a Session. Hibernate will detect any changes made to anobject in persistent state and synchronize the state with the database whenthe unit of work completes.(transitive persistence) . Any changes made to theobject in persistent state are automatically updated during transaction time.

    Detached- A detached instance is an object that has been persistent, butits Session has been closed. The reference to the object is still valid, ofcourse, and the detached instance might even be modified in this state. Adetached instance can be reattached to a new Session at a later point in time,making it (and all the modifications) persistent again. This feature enables a

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    8/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 8 of 28

    programming model for long running units of work that require user think-time.These are called application transactions, i.e. a unit of work from the point ofview of the user.

    Automatic dirty checking: Inside a transaction, if changes are

    made to the state of the persistent object, there is no need to explicitly call thesession.update() , the modified state is committed to the database at thetransaction commit time.As long as the object is inpersistentstate that is, bound to a particularHibernate Session (i.e. they have been just loaded or saved in a unit of work),Hibernate detects any changes to the persistent entity state and executesSQL in a write-behind fashion. The process of synchronizing the memorystate with the database, usually only at the end of a unit of work, is calledflushing

    Session session = sessions.openSession();

    Transaction tx = session.beginTransaction();Person person = (Person) session.get(Person.class, new Long(userID));person.setPassword("secret");tx.commit(); // we are not invoking update() method. dirty checkingsession.close();

    Hibernate Types

    To understand the behaviour of various Java language-level objects withrespect to the persistence service, we need to classify them into two groups:

    Entity Type:An object ofentitytype has its own database identity (primary key value). Anobject reference to an entity is persisted as a reference in the database (aforeign key value). An entity has its own lifecycle; it may exist independentlyof any other entity. The entity types are shared( when loaded from database)

    Entities must be explicitly saved and deleted (except that saves and deletionsmay be cascaded from a parent entity to its children). An entity's persistentstate consists of references to other entities and instances of value types.

    Value Type:An object ofvalue type has no database identity; it belongs to an entity, andits persistent state is embedded in the table row of the owning entity. Valuetypes dont have identifiers or identifier properties. The lifespan of a value-type instance is bounded by the lifespan of the owning entity. Value types arenot shared. A value type instance is owned by exactly one entity when itsretrieved from the database its never shared.

    Values are primitives, collections (not what's inside a collection), componentsand certain immutable objects. all types (classes) provided by the JDK havevalue type semantics in Java, while user-defined types may be mapped with

    entity or value type semantics

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    9/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 9 of 28

    Basic value types

    The built-in basic mapping types may be roughly categorized intointeger, long, short, float, double, character, byte, boolean, yes_no, true_falseType mappings from Java primitives or wrapper classes to appropriate

    (vendor-specific) SQL column types. boolean, yes_no and true_false are allalternative encodings for a Java boolean or java.lang.Boolean.stringA type mapping from java.lang.String to VARCHAR (or Oracle VARCHAR2).

    date, time, timestampType mappings from java.util.Date and its subclasses to SQL types DATE,TIME and TIMESTAMP (or equivalent).

    calendar, calendar_dateType mappings from java.util.Calendar to SQL types TIMESTAMP and DATE(or equivalent).

    big_decimal, big_integerType mappings from java.math.BigDecimal and java.math.BigInteger toNUMERIC (or Oracle NUMBER).

    locale, timezone, currencyType mappings from java.util.Locale, java.util.TimeZone andjava.util.Currency to VARCHAR (or Oracle VARCHAR2). Instances of Locale

    and Currency are mapped to their ISO codes. Instances of TimeZoneare mapped to their IDclassA type mapping from java.lang.Class to VARCHAR (or Oracle VARCHAR2). AClass is mapped to its fully qualified name.binaryMaps byte arrays to an appropriate SQL binary type.textMaps long Java strings to a SQL CLOB or TEXT type.serializableMaps serializable Java types to an appropriate SQL binary type. You may

    also indicate the Hibernate type serializable with the name of a serializableJava class or interface that does not default to a basic type.

    clob, blobType mappings for the JDBC classes java.sql.Clob and java.sql.Blob. Thesetypes may be inconvenient for some applications, since the blob or clob objectmay not be reused outside of a transaction. (Furthermore, driver support ispatchy and inconsistent.)

    Important Mappings

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    10/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 10 of 28

    many-to-one:An ordinary association to another persistent class isdeclared using a many-to-one element. The relational model is a many-to-oneassociation: a foreign key in one table is referencing the primary keycolumn(s) of the target table.

    name: The name of the property.column (optional): The name of the foreign key column. This may also bespecified by nested element(s).class (optional - defaults to the property type determined by reflection): Thename of the associated class.

    cascade (optional): Specifies which operations should be cascaded from theparent object to the associated object.update, insert (optional - defaults to true) specifies that the mapped columnsshould be included in SQL UPDATE and/or INSERT statements. Setting bothto false allows a pure "derived" association whose value is initialized fromsome other property that maps to the same colum(s) or by a trigger or otherapplication.property-ref: (optional) The name of a property of the associated class that isjoined to this foreign key. If not specified, the primary key of the associatedclass is used.unique (optional): Enable the DDL generation of a unique constraint for the

    foreign-key column. Also, allow this to be the target of a property-ref. Thismakes the association multiplicity effectively one to one.not-null (optional): Enable the DDL generation of a nullability constraint forthe foreign key columns.

    composite-id

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    11/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 11 of 28

    For a table with a composite key, you may map multiple properties of theclass as identifier properties. The element accepts property mappings as child elements. Your persistent class mustoverride equals() and hashCode() to implement composite identifier equality.It must also implements Serializable.

    one-to-one

    A one-to-one association to another persistent class is declared using a one-to-one element.

    name: The name of the property.class (optional - defaults to the property type determined by reflection): Thename of the associated class.cascade (optional) specifies which operations should be cascaded from theparent object to the associated object.fetch (optional - defaults to select): Chooses between outer-join fetching or

    sequential select fetching.property-ref: (optional) The name of a property of the associated class that isjoined to the primary keyof this class. If not specified, the primary key of the associated class is used.access (optional - defaults to property): The strategy Hibernate should use foraccessing the property value.lazy (optional - defaults to proxy): By default, single point associations areproxied. lazy="no-proxy" specifies that the property should be fetched lazilywhen the instance variable is first accessed (requires build-time bytecodeinstrumentation). lazy="false" specifies that the association will always beeagerly fetched.

    subclass

    For the table-per-class-hierarchy mapping strategy, the declaration is used.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    12/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 12 of 28

    .....

    name: The fully qualified class name of the subclass.discriminator-value (optional - defaults to the class name): A value thatdistiguishes individual subclasses.lazy (optional, defaults to true): Setting lazy="false" disables the use of lazyfetching.

    Each subclass should declare its own persistent properties and subclasses. and properties are assumed to be inherited from the rootclass. Each subclass in a heirarchy must define a unique discriminatorvalue.If none is specified, the fully qualified Java class name is used.

    joined-subclass

    Each subclass may be mapped to its own table (table-per-subclass mappingstrategy). Inherited state is retrieved by joining with the table of thesuperclass. We use the element.

    .....

    name: The fully qualified class name of the subclass.table: The name of the subclass table.

    proxy (optional): Specifies a class or interface to use for lazy initializingproxies.lazy (optional, defaults to true): Setting lazy="false" disables the use of lazyfetching

    No discriminator column is required for this mapping strategy. Each subclassmust, however, declare a table column holding the object identifier using the element.

    union-subclass

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    13/28

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    14/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 14 of 28

    key

    It appears in the parent mapping element defines a join to a new table, anddefines the foreign key in the joined table, that references the primary key ofthe original table.

    column (optional): The name of the foreign key column. This may also bespecified by nested element(s).on-delete (optional, defaults to noaction): Specifies whether the foreign keyconstraint has databaselevel cascade delete enabled.property-ref(optional): Specifies that the foreign key refers to columns that

    are not the primary key of the orginal table. (Provided for legacy data.)not-null (optional): Specifies that the foreign key columns are not nullable(this is implied whenever the foreign key is also part of the primary key).update (optional): Specifies that the foreign key should never be updated (thisis implied whenever the foreign key is also part of the primary key).unique (optional): Specifies that the foreign key should have a uniqueconstraint (this is implied whenever the foreign key is also the primary key).

    Collection Mapping

    Persistent collectionsHibernate requires that persistent collection-valued fields be declared as aninterface type, for example:

    public class Product {private String serialNumber;private Set parts = new HashSet();public Set getParts() {

    return parts;}

    void setParts(Set parts) {this.parts = parts;

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    15/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 15 of 28

    }public String getSerialNumber() {

    return serialNumber;}void setSerialNumber(String sn) {

    serialNumber = sn;}

    }

    The actual interface might be java.util.Set, java.util.Collection, java.util.List,java.util.Map, java.util.SortedSet, java.util.SortedMap

    Collections instances have the usual behavior of value types. They areautomatically persisted when referenced by a persistent object andautomatically deleted when unreferenced. If a collection is passed from onepersistent object to another, its elements might be moved from one table to

    another.

    Collection foreign keys

    Collection instances are distinguished in the database by the foreign key ofthe entity that owns the collection.This foreign key is referred to as the collection key column (or columns) of thecollection table. The collection key column is mapped by the element.There may be a nullability constraint on the foreign key column. For mostcollections, this is implied. For unidirectional one to many associations, the

    foreign key column is nullable by default, so you might need to specifynot-null="true".

    Here, represents foreign key column in address table which refers tothe primary key personid of the person table

    Associations

    One-to-many association unidirectional

    A one to many association links the tables of two classes via a foreign key,

    with no intervening collection table.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    16/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 16 of 28

    class (required): The name of the associated class.

    element does not need to declare any columns. Nor is itnecessary to specify the table name anywhere.

    many to one uni-directional

    one to one unidirectional

    A unidirectional one-to-one association on a foreign key is almost identical.The only difference is the column unique constraint.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    17/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 17 of 28

    making associations bidirectional

    Object-oriented languages represent associations using object references andcollections of object references. In the relational world, an association isrepresented as a foreign keycolumn,

    Object references are inherently directional; the association is from one objectto the other. If an association between objects should be navigable in bothdirections, you must define the association twice, once in each of theassociated classes

    class person{

    private Address address;----

    }

    class Address{private Person person;

    }

    On the other hand, foreign key associations arent by nature directional. Infact, navigation has no meaning for a relational data model, because you cancreate arbitrary data associations with table joins andprojection.

    In order to make a relation bi-directional the following changes arenecessary. Lets take the example, person & address bi-directional one-to-

    many relation

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    18/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 18 of 28

    1) Java code.: There should be references from person to address andaddress to person.

    2) hbm.xml :The column mapping defined by the element in is foreign keycolumn of the associated address table. Notice that in the mapping for themany-to-one association we specified same column as foreign key column.

    Now we have two different unidirectional associations mapped to the sameforeign key, which poses a problem. At runtime, there are two different in-

    memory representations of the same foreign key value: the Person propertyof Address and an element of the address collection held by an person.

    Now, our TestMain class has code like this,addresses.add(address);address.setPerson(person);

    Hibernate detects two different changes to the in-memory persistentinstances. From the point of view of the database, just one value must beupdated to reflect these changes: the personid column of theBID table. Hibernate doesnt transparently detect the fact that the twochanges refer to the same database column, since at this point weve donenothing to indicate that this is a bidirectional association.

    We need one more thing in our association mapping to tell Hibernate to treatthis as a bidirectional association: The inverse attribute tells Hibernate that thecollection is a mirror image of the many-to-one association on the other side:

    Without the inverse attribute, Hibernate would try to execute two different SQLstatements, both updating the same foreign key column, when we manipulatethe association between the two instances. By specifying inverse="true", weexplicitly tell Hibernate which end of the association it should synchronize withthe database.In this example, we tell Hibernate that it should propagate changes madeat the Address end of the association to the database, ignoring changesmade only to the address collection on the person side. Thus if we only callperson.getAddresses().add(address), no changes will be made persistent.

    This is consistent with the behavior in Java without Hibernate: If anassociation is bidirectional, you have to create the link on two

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    19/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 19 of 28

    sides, not just one.

    one to one bi-directional

    property-ref: (optional) The name of a property of the associated class that isjoined to the primary key of this class. If not specified, the primary key of theassociated class is used.

    many-to-many unidirectional

    One Category has many items and one item has many categories. Many-to-many association always require a link table. In this association, there would

    be 3 tables, one for category, one for item and third table is a link tablecategory_item. Link table consists of the two columns categoryid and itemid.Categoryid has foreign key relation to primary key of the category table. itemidhas the foreign key relation to the primary key of the Item table. The primarykey of the link table is composed of both columns in link table.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    20/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 20 of 28

    points to observe:1. element. the collection table is CategoryItem. key refers to

    category_id in CategoryItem table and category_id has foreign keyrelation to the primary key of the category table.

    2. element. This refers to the item_id column in theCategoryItem table and the item_id has foreign key relation to theprimary key of the Item table. tag has attribute classwhich denotes the association class.

    many-to-many bidirectional

    the principle inverse=true applies for Many-to-Many bidirectional relation

    also.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    21/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 21 of 28

    Each row of the link table is represented by two collection elements, oneelement at each end of the association. An association between an Item anda Category is represented in memory by the Item instance belonging to theitems collection of the Category but also by the Category instance belongingto the categories collection of the Item.

    The ocde to create the object association also changes.

    cat.getItems.add(item);item.getCategories().add(category);

    When you map a bidirectional many-to-many association, you must declareone end of the association using inverse="true" to define which sides state isused to update the link table. We can chose any side as inverse side.

    inverse="true" setting tells Hibernate to ignore changes made to the

    categories collection and use the other end of the association (the itemscollection) as the representation that should be synchronized with thedatabase if we manipulate the association in Java code.

    Inheritance mapping Strategies

    Table per class hierarchy

    An entire class hierarchy could be mapped to a single table. Thistable would include columns for all properties of all classes in the hierarchy.

    The concrete subclass represented by a particular row is identified by thevalue of a type discriminatorcolumn.

    discriminator column is a special column to distinguish between persistentclasses. This isnt a property of the persistent class; its used internally byHibernate. Hibernate will automatically set and retrieve the discriminatorvalues.

    There is one major problem: Columns for properties declared by subclassesmust be declared to be nullable. If your subclasses each define several non-nullable properties, the loss of NOT NULL constraints could be a serious

    problem from the point of view of data integrity.

    In Hibernate, we use the element to indicate a table-per-classhierarchy mapping. Every subclass has its own element.

    Table per subclassAnother option is to represent inheritance relationships as relational foreignkey associations. Everysubclass that declares persistent properties has itsown table. So, Super class has its own table and properties of superclass arepersisted to that table.All the subclasses have separate tables and the instance data of eachsubclass is inserted into tables (related to subclass). The table for subclass

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    22/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 22 of 28

    contains columns only for each non-inheritedproperty (each propertydeclared by the subclass itself) along with a primary key that is also a foreignkey of the superclass table.

    Note On primary key: tag is used here. The primary key of the

    subclass table has a foreign key association to the primary key of thesuperclass table.The two rows are linked together by their shared primary key value. Later, thesubclass instance may be retrieved from the database by joining the subclasstable with the superclass table.

    The primary advantage of this strategy is that the relational model iscompletely normalized. Schema evolution and integrity constraint definitionare straightforward. In Hibernate, we use the element toindicate a table-per-subclass mapping.

    A element may contain other elementsbut not a element. Hibernate doesnt support mixing of these twomapping strategies.

    disadvantages: performance may be unacceptable for complex classhierarchies.

    Table per concrete class

    This strategy uses one table for each (non-abstract) class All properties of aclass, including inherited properties, could be mapped to columns of this

    table, In our example, there are 3 classes. Account and its subclassesSavingAccount and CurrentAccount. In this case, 2 tables are created, one forSavingAccount and one for CurrentAccount. All the instance variables ofSavingAccount, including the variables for Account class, are inserted to theSavingAccount table. There is no table for superclass data as in table persubclass strategy.

    is used for this strategy.

    ...

    ...

    ...

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    23/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 23 of 28

    here 2 tables are involved. one for CreditCardPayment and one forCashPayment.

    Hibernate Query Language

    HQL is fully object-oriented query language. The Query and Criteria interfacesboth define several methods for controlling execution of a query.

    The query interfaces

    An object-oriented representation of a Hibernate query. A Query instance isobtained by calling Session.createQuery().

    The createQuery() method prepares an HQL query: The simplest possible

    query is

    from Person , which returns all instances of person. (include packagename). Select clause is not mandatory unlike SQL.

    from person p . p is alias which is common in sql.

    Query hqlQuery = session.createQuery("from Person");

    Multiple classes may appear, resulting in a cartesian product or "cross" join.

    Query hqlQuery = session.createQuery("from Person, Address");

    where clasue

    The where clause is used to express a restriction in both SQL and HQL;

    1. from person p where p.id between 1 and 10.2. from Person p where p.name in ('sreedhar','krsna')3. from User u where u.email is null4. from User u where u.email is not null

    5. from Person p where p.name like 'tcube%'6. where user.firstname like "G%" and user.lastname like "K%"7. from Person p order by p.name desc

    HQL join options

    In Hibernate queries, it is not necessary to specify a join condition explicitly. Ifwe specify the name of a mapped Java class association in the query,Hibernate can deduce the table join expression For example, the Personclass has an association named addresses with the Address class.from Person p join p.addresses

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    24/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 24 of 28

    HQL provides four ways of expressing (inner and outer) joins:1. An ordinaryjoin in the from clause2. A fetchjoin in the from clause3. An implicitassociation join

    The supported join types are borrowed from ANSI SQL inner join left outer join right outer join full join (not usually useful)

    ordinaryjoin in the from clause:

    In the below example, aliases are used.

    from Person pjoin p.addresses awhere p.description like '%abc%'and a.city like Hyd%

    In the ordinary join, if there is no select clause, the result would be aCartesian product. The generated SQL is as follows

    select person0_.id as id0_0_, addresses1_.addressid as addressid1_1_,person0_.version as version0_0_, person0_.name as name0_0_,

    addresses1_.version as version1_1_, addresses1_.city as city1_1_,addresses1_.street as street1_1_, addresses1_.personid as personid1_1_from person person0_ inner join address addresses1_ onperson0_.id=addresses1_.personid where addresses1_.city like 'Hyd%'

    The query returns all combinations of associated Person and Address. Butunlike a fetch join, the addresses collection of the Person isnt initialized bythe query. Query returns an ordered pair: (Person, Address). In the queryresult, Hibernate represents an ordered pair as an array.

    List list = q.list();System.out.println("size of list is.."+ list.size());Iterator itr = list.iterator();while(itr.hasNext()){

    Object[] obj = itr.next();Person p = (Person)obj[0];

    Address a = (Address)obj[1];System.out.print(p.getName() + " ");System.out.println(a.getCity());}

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    25/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 25 of 28

    Instead of a List of Items, this query returns a List of Object[] arrays. At index0 is the Person, and at index 1 is the Address. A particular Person mayappear multiple times, once for each associated Address.

    Select Clause

    we dont want the Address in the query result, we can specify a select clausein HQL. This clause is optional in HQl. select clause is mandatory in SQL.We can use the select clause to retrieve only the selected objects:

    select pfrom Person p

    join p.addresses adrswhere p.description like '%abc%'and adrs.city like Hyd%

    The generated SQL is as follows

    select person0_.id as id0_, person0_.version as version0_,person0_.name as name0_ from person person0_ inner join addressaddresses1_ on person0_.id=addresses1_.personid

    The query result contains just Persons, and because its an inner join, onlyPersons who have address.

    Query q = session.createQuery("select p from Person p join p.addresses");

    List list = q.list();Iterator itr = list.iterator();while(itr.hasNext()){

    Person p = itr.next();System.out.println(p.getName() + " ");

    }

    fetch join in the from clause

    In HQL, you can specify that an association should be eagerly fetched by an

    outer join using the fetch keyword in the from clause:

    from Person pleft join fetch p.addresseswhere p.name like '%tcube%'

    This query returns all Persons with a name that contains the string tcube, andall their addresses, in a single select. When executed, it returns a list ofPerson instances, with their addresses collection fully initialized. We call this afrom clause fetch join.The purpose of a fetch join is performance optimization: We use this syntax

    only because we want eager initialization of the address collections in a singleSQL select.

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    26/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 26 of 28

    HQL always ignores the mapping document eager fetch (outer join) setting. Ifyouve mapped some associations to be fetched by outer join (by settingouter-join="true" on the association mapping), any HQL query will ignorethis preference. You must use an explicit fetch join if you want eager fetching

    in HQL. HQL will not ignore fetch=subselect in collection mapping.

    Implicit Joins

    from Address a where a.person.name like '%Foo%'This results in an implicit join on the many-to-one associations from Addressto Person the name of this association is item.Hibernate knows that you mapped this association with the person_ID foreignkey in the Address table and generates the SQL join condition accordingly.Implicit joins are always directed along many-to-one or one-to-oneassociations, never through a collection-valued association (you cantwrite person.addresses.city).

    the generated sql would be as follows:

    select address0_.addressid as addressid1_, address0_.version as version1_,address0_.city as city1_, address0_.street as street1_, address0_.personid aspersonid1_ from address address0_, person person1_ whereaddress0_.personid=person1_.id and person1_.name='john'

    Theta Style Joinsthe theta-style syntax is useful when your join condition isnt a foreign keyrelationship mapped to a class association

    Using batch fetchingHibernate can make efficient use of batch fetching, that is, Hibernate can loadseveral uninitialized proxies if one proxy is accessed (or collections). Batchfetching is an optimization of the lazy select fetching strategy.There are two ways you can tune batch fetching: on the class and thecollection level.

    If we enable batch fetching on collections, the behaviour would be as follows.

    For example, if each Person has a lazy collection of Addresses and 10persons are currently loaded in the Sesssion, iterating through all persons willgenerate 10 SELECTs, one for every call to getAddresses(). If you enablebatch fetching for the cats collection in the mapping of Person, Hibernatecan pre-fetch collections:

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    27/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 27 of 28

    If we enable batch fetching on class, the behaviour would be as follows.

    You have 25 Cat instances loaded in a Session, each Cat has a reference toits owner, a Person. The Person class is mapped with a proxy, lazy="true". Ifyou now iterate through all cats and call getOwner() on each, Hibernate will by

    default execute 25 SELECT statements, to retrieve the proxied owners. Youcan tune this behaviour by specifying a batch-size in the mapping of Person:

    ...

    Criteria Query

    The simplest criteria query looks like this:session.createCriteria(Item.class);It retrieves all persistent instances of the Item class. This is also called theroot entityof the criteria query.

    The Criteria interface also supports ordering of results with the addOrder()method and the Order criterion:session.createCriteria(User.class).addOrder( Order.asc("lastname") ).addOrder( Order.asc("firstname") );

    Applying restrictions

    For a criteria query, you must construct a Criterion object to express aconstraint.The Restrictions class provides factory methods for built-in Criteriontypes.

    Criterion emailEq = Restrictions.eq("email", "[email protected]");Criteria crit = session.createCriteria(User.class);crit.add(emailEq);

    User user = (User) crit.uniqueResult();

    Creating innerjoin

    Criteria crit = s.createCriteria(Person.class);

    crit = crit.createCriteria("addresses");

    Dynamic Association Fetching

    List cats = sess.createCriteria(Person.class).add( Restrictions.like("name", "Fritz%") )

  • 7/31/2019 Hibernate Concepts Students[1] Krsna-t-cube

    28/28

    Krsna T-CUBE Software Consulting private Limited (Teach, Train, Transform)

    Page 28 of 28

    .setFetchMode("addresses", FetchMode.EAGER)

    .list();

    SecondLevel cache

    One major advantage of using Hibernate is the caching feature provided by it.

    A cache keeps a representation of current database state close to theapplication, either in memory or on disk of the application server machine.The cache is a local copy of the data. The cache sits between your applicationand the database. Read-only data or mostly read-only can be cached insecond level cache. Instead of hitting the database every time, the applicationlooks in the second-level cache for the existence of the data. Applicationretrieves the data from database only if the data is not present in the second-level cache.

    The cache may be used to avoid a database hit whenever1. The application performs a lookup by identifier (primary key)2. The persistence layer resolves an association lazily

    Good candidate classes for caching are classes that represent Data that changes rarely Non-critical data (for example, content-management data) Data that is local to the application and not shared

    Bad candidates for second-level caching are

    Data that is updated often Financial data Data that is shared with a legacy application

    Enabling the second-level cache involves the following steps.1) enable it at the global level2) Chose a cache provider.3) enable it at the mapping level(hbm.xml)

    The following cache implementations are built-in in the HibernateEHCache, OpenSymphony OSCache SwarmCache JBossCache