+ All Categories
Home > Documents > Hibernate One

Hibernate One

Date post: 04-Jun-2018
Category:
Upload: ranjitha-bachina
View: 229 times
Download: 0 times
Share this document with a friend

of 21

Transcript
  • 8/13/2019 Hibernate One

    1/21

    Difference between JDBC and Hibernate?

    Hibernate is database independent, the code will work for all kinds of database like derby,

    MySQL, oracle, SQLServer etc. Where as in JDBC query must be database specific.

    As hibernate is set of objects, no need of SQL knowledge. In jdbc sql knowledge is must.

    In hibernate, criteria query take care of query tuning. In case of JDBC you need to tune your

    query.

    As hibernate supports two level of cache, you can store data into catch for better performance

    while in JDBC you need to implement your java code.

    Hibernate supports query cache and it will provide the statistics about your query and database

    status. JDBC doesnt provides any statistics.

    Development fast in case of Hibernate because you dont need to write queries.

    No need to create any connection pool in case of hibernate. You can use c3p0. In case of JDBC

    we need to create our own connection pool.

    In the xml file you can see all the relation between tables in case of hibernate, Easy readability.

    You can load your objects on start up using lazy=false in case of hibernate. But JDBC dont have

    such support.

    Hibernate supports automatic versioning of rows but JDBC not.

    Hibernate supports inheritance, associations, collections.

    In hibernate if we save the derived class object, then its base class object will also be stored into

    database, it means hibernate supporting inheritance.

    Hibernate supports relationships like one-to-many, one-to-one, many-to-many, many-to-one.

    Hibernate also supports collections like List, Set, Map(Only new collections).

    In JDBC all exceptions are checked exceptions, so we must write code in try, catch and throws

    but in hibernate we only have unchecked type exceptions, so no need to write try, catch or

    throws. Actually in hibernate we have the translator which converts checked to unchecked.

    Hibernate has capability to generate primary keys automatically while we are storing therecords in database.

    Hibernate has its own query language, i.e. HQL (hibernate query language) which is database

    independent.

    While we are inserting any record, if we dont have any particular table in the database, JDBC

    will rises an error like VIEW no exist, and throws exception, but in case of hibernate, if it not

    found any table in the database this will create table for us.

    Hibernate supports caching mechanism by this, the number of round trips between an

    applications and the database will be reduced, by using this caching technique an applications

    performance will be increased automatically.

    Hibernate supports annotations, apart from XML. Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we

    use the methods provided by that API.

    Getting pagination in hibernate is quite simple.

    =====================================================================================

  • 8/13/2019 Hibernate One

    2/21

    What is hibernate template?

    Org.springframework.orm.

    different methods for quer

    HibernateException into un

    ============================

    What are the benefits does Hibern

    The benefits of HibernateTemplate

    HibernateTemplate, a sprin

    Common functions are sim

    Sessions are automatically

    Commit or rollback transac

    executed.

    Exceptions are automatical

    HibernateTemplate class g

    ============================

    What is difference between sorted

    Sorted collection:

    A sorting collection is sorti

    collections framework. The

    the data being read from d

    If your collection is not larg

    Order collection:

    Order collection is sorting

    this when retrieval.

    If your collection is very lar

    ============================

    What is ORDER BY clause?

    The ORDER BY keyword is

    The ORDER BY keyword sor

    descending order, you can

    ibernate.HibernateTemplate is a helper class whic

    ying/retrieving data from the database. It also conv

    checked DataAccessExceptions.

    =========================================

    teTemplate provide?

    are:

    g template class simplifies interactions with hibern

    plified to single method calls.

    opened, closed after your code executed.

    tions are automatically done by template class, aft

    ly caught and converted to runtime exceptions.

    t deprecated from hibernate 4.x.

    =========================================

    and ordered collection in hibernate?

    g a collection by utilizing the sorting features provi

    sorting occurs in the memory of JVM which runnin

    atabase using java comparator.

    e, it will be more efficient way to sort it.

    collection by specifying the order-by clause for sor

    ge, it will be more efficient way to sort it.

    =========================================

    sed to sort the resultset by one or more columns.

    ts the records in ascending order by default. To sor

    use the DESC keyword.

    provides

    erts checked

    ==============

    ate session.

    r your code

    ==============

    ded by the java

    g hibernate, after

    ting this collection

    ==============

    the records in a

  • 8/13/2019 Hibernate One

    3/21

    =====================================================================================

    What the collections types are in hibernate?

    Bag

    Set

    List

    Array

    Map

    =====================================================================================

    What is lazy fetching in hibernate?

    Lazy fetching is associated with child objects loading for its parents. While loading the parent,

    the selection of loading a child object is to be specified/mentioned in the hbm.xml file.

    Hibernate does not load the whole child objects by default. Lazy=true means not to load the

    child objects.

    =====================================================================================

    Lifecycle of pojo class objects?

    Pojo class object having 3 states:

    Transient state

    Persistent state

    Detached state

    Transient and Persistent states:

    Whenever an object of a pojo class is created then it will be in the transient state.

    When the object is in a transient state it doesnt represent any row of the database, I mean not

    associated with any session object, if we speak more we can say no relation with the database

    its just an normal object.

    If we modify the data of a pojo class object, when it is in transient state then it doesnt effect on

    the database table.

    When the object is in persistent state, then it represent one row of the database, if the object is

    in persistent state then it is associated with the unique session.

    If you want to move an object from persistent to detached state, we need to do either closing

    that session or need to clear the cache of the session.

    If we want to move an object from persistent state into transient state then we need to deletethat object permanently from the database.

  • 8/13/2019 Hibernate One

    4/21

    Note:

    See the above client program, line numbers 16 to 19 we just loaded the object and called the

    corresponding setters methods, its not related to the database row.

    If you see, line number 24 we called save method in the session interface, means the object is

    now having the relation with the database.

    If we want to convert the object from transient state to persistent state we can do in 2 ways

    o By saving that object like above.o By loading object from database.

    If we do any modifications all the changes will first applied to the object in session cache only (let we do

    the modifications 5 times, then 5 times we need to save the changes into the database right, which

    means number of round trips from our application to database will be increased, Actually if we load an

    object from database, first it will saves in the cache-memory so if we do any number of changes all will

  • 8/13/2019 Hibernate One

    5/21

    be affected at cache level only and finally we can call save or update method so with the single call of

    save or update method the data will be saved into the database.)

    If we want to save an object into database then we need to call any one of the following methods:

    Save()

    Persist() SaveOrUpdate()

    Transient state:

    One newly created object, without having any relation with the database, means never persisted, not

    associated with any session object.

    Persistent state:

    Having the relation with the database, associated with a unique session object.

    Detached state and Detached state to Persistent state conversion:

  • 8/13/2019 Hibernate One

    6/21

    When close the session object, the persistent instance will become a detached instance.

    Notes:

    We have opened the session1 at line number 14 and closed at line number 20, see have been

    loaded the product class object by using get() method.

    Remember get() method always returns the super class object. See line number 22, iam trying to change the price, but it wont effect the database because its

    not in the session cache so I need to take one more session to update this value in the database,

    so for that reason I took one more session from line numbers 24 30.

    =====================================================================================

    What the core interfaces are of hibernate framework?

    Session interface.

    SessionFactory interface.

    Transaction interface.

    Query and Criteria interface.

    =====================================================================================

    What the different types of caches are in hibernate?

    Two types of caches provided by hibernate:

    First-level cache:

    First level cache is associated with the session object.

    By default hibernate uses first-level cache on a per-transaction basis.

    Hibernate mainly uses this cache mainly to reduce the number of SQL queries it needs togenerate within a given transaction.

    Second-level cache:

    Second level cache is associated with the SessionFactory object.

  • 8/13/2019 Hibernate One

    7/21

    ============================

    How does hibernate second-level c

    Hibernate always tries to fi

    from the second-level cach

    If this fails again, the object Hibernates static initialize(

    second-level cache before

    for manipulation proxies.

    ============================

    What is a query cache in hibernate

    The query cache is responsi

    objects returned by querie

    Query cache does not cach

    identifier values and result

    Hibernate stores timestam

    new record then will fire q

    This will always return youquery.

    Query cache is an optional

    the cached query results a

    queries that are run freque

    ============================

    What is hibernate caching?

    Caching is all about application per

    database to avoid the number of d

    performance critical applications.

    ============================

    What is callback interface in hibern

    Callbacks interfaces allow the appli

    to an object. Example: when an obj

    implement these callbacks, but the

    =========================================

    ache work?

    rst retrieve objects from the session and if this fails

    e.

    s are directly loaded from the database. ) method, which populates a proxy object, will atte

    oing to the database. The hibernate class provides

    =========================================

    ible for caching the results and to be more precise t

    .

    e the state of the actual entities in the resultset; it

    of value type.

    s along with query to track new records and if hib

    ery again evicting old data.

    updated record because actual state object was ne

    feature and requires two additional physical cache

    d the timestamps when a table was last updated. T

    ntly with the same parameters.

    =========================================

    ormance optimization and it sits between your app

    tabase hits as many as possible to give a better pe

    =========================================

    ate?

    cation to receive a notification when something int

    ect is loaded, saved, or deleted. Hibernate applicati

    y are useful for implementing certain kinds of gene

    ==============

    it tries to retrieve

    pt to hit the

    static methods

    ==============

    he keys of the

    ache only

    rnate found a

    er cached with

    regions that hold

    his is useful for

    ==============

    lication and the

    formance for

    ==============

    resting happens

    ons dont need to

    ic functionality.

  • 8/13/2019 Hibernate One

    8/21

    =====================================================================================

    What is difference between update() and merge() method?

    Both methods in hibernate are used to convert the object which is in detached state into persistence

    state.

    Note:

    See from line numbers 6-9, we just loaded one object s1 into session1 cache and closed session1 at line

    number 9, so now object s1 in the session1 cache will be destroyed as session1 cache will expireswhenever we say session1.close.

    Now s1 object will be in some RAM location, not in the session1 cache.

    Here s1 is in detached state, and at line number 11 we modified that detached object s1, now if we call

    update() method then hibernate will an error, because we can update the object in the session only.

    So we opened another session[session2] at line number 13, and again loaded the same student object

    from the database, but with name s2.

    So in this session2, we called session2.merge(s1); now into s2 object s1 changes will be merged and

    saved into the database.

    =====================================================================================

  • 8/13/2019 Hibernate One

    9/21

    What difference between load and get method?

    Load method:

    It throws ObjectNotFoundException if supplied id is not found.

    Load just returns a proxy by default and database wont be hit until proxy is first invoked.

    Get method:

    It returns null, if supplied id is not found.

    Get will hit the database immediately.

    =====================================================================================

    What are the different caching strategies?

    Read-only:

    This strategy is useful for data that is read frequently but never updated. This is by far the

    simplest and best-performing cache strategy.

    Read/write:

    Read/write caches may be appropriate if your data needs to be updated. They carry more

    overhead than read-only caches. In non-JTA environments, each transaction should be

    completed when session.close() or session.disconnect() is called.

    Nonstrict read/write:

    This strategy does not guarantee that two transactions wont simultaneously modify the same

    data. Therefore, it may be most appropriate for data that is read often but only occasionally

    modified.

    Transactional:

    This is fully transactional cache that may be used only in a JTA environment.

    =====================================================================================

    What is version checking in hibernate?

    Version checking used in hibernate when more than one thread trying to access same data.

    Example:

    User-A edit the row of the TABLE for update (in the user interface changing data this is user

    thinking time) and in the same time User-B edit the same record for update and click the

    update. Then User-A click the update and update done. Change made by User-B gone. In

    hibernate you can prevent slate object updation using version checking.

  • 8/13/2019 Hibernate One

    10/21

    Check the version of the ro

    you are fetching the row of

    number and match with yo

    ============================

    Difference between getCurrentSes

    getCurrentSession () :

    A session is opened when

    when the transaction ends

    Every time it returns same

    openSession ():

    If you decide to use manag

    have to flush() and close() i

    Every time it returns differ

    ============================

    What does session.refresh() do?

    It is possible to reload an o

    This is useful when databa

    ============================

    How to get JDBC connections in hib

    User session.connection()

    ============================

    Whats the use of session.lock() in

    Session.lock() method of se

    This method of reattaching

    reattaching the object and

    ============================

    What is the difference between th

    Both of these methods and

    object.

    w when you are updating the row. Get the version

    the TABLE for update. On the time of updation just

    ur version number (on the time of fetching).

    =========================================

    ion () and openSession () in hibernate?

    etCurrentSession() method is called for the first tim

    automatically.

    session object.

    e the session yourself then go for SessionFactory.o

    t. It does not flush and close() automatically.

    nt session object.

    =========================================

    bject and all its collections at any time, using the re

    e triggers are used to initialize some of the propert

    =========================================

    ernate?

    ethod to get JDBC connection.

    =========================================

    hibernate?

    ssion is used to reattach an object which has been

    doesnt check for any data synchronization in data

    hence may lead to lack of synchronization in data.

    =========================================

    session.update() method and the session.lock() m

    saveOrUpdate() method are intended for reattachi

    f the row when

    fetch the version

    ==============

    e and closed

    enSession(), you

    ==============

    esh() method.

    ies of the object.

    ==============

    ==============

    detached earlier.

    ase while

    ==============

    ethod?

    ng a detached

  • 8/13/2019 Hibernate One

    11/21

    The lock() method simply reattaches the object to the session without checking or database on

    the assumption that the database in sync with the detached object.

    It is best practice to use either update() or saveOrUpdate() method.

    Use lock() method only if you are absolutely sure that the detached object is in sync with your

    detached object or if it does not matter because you will be overwriting all the columns that

    would have changed later on within the same transaction.

    =====================================================================================

    What is sessionFactory interface?

    The sessionFactory is the concept that is a single data store and thread safe.

    It is thread safe.

    The cache that is immutable of compiled mappings for a specific database.

    A sessionFactory will be built only at the time of its startup.

    In order to access it in the application code, it should be wrapped in singleton.

    =====================================================================================

    What is session interface?

    This represents hibernate session which perform the manipulation on the database entities.

    Session manages persistence state, fetching persisted ones and management of the transaction

    demarcation.

    =====================================================================================

    Explain about the dirty checking feature of hibernate?

    Dirty checking is a feature of hibernate that saves time and effort to update the database when

    states of objects are modified inside a transaction. All persistent objects are monitored by

    hibernate. It detects which objects have been modified and then calls update statements on all

    updated objects.

    Hibernate session contains a PersistenceContext object that maintains a cache of all the objects

    read from the database as a Map. So, when you modify an object within the same session.

    Hibernate compares the objects and triggers the updates when the session is flushed. The

    objects that are in the PersistenceContext are persistent objects.

    =====================================================================================

    Explain about mapping description file?

    This mapping file has an extension .hbm.xml which instructs mapping between java class and

    database tables.

    =====================================================================================

  • 8/13/2019 Hibernate One

    12/21

    What is addClass function?

    This function translates a j

    as an input stream from th

    efficient usage of classes in

    ============================

    How can a whole class be mapped

    Mark the class as mutable=

    By default it is true.

    ============================

    What is hibernate tuning?

    The key to obtain better pe

    Optimization, Session Man

    ============================

    How to execute stored procedure i

    ============================

    Difference between SQL and HQL?

    HQL uses pojo-class-name i

    column-name for retrievin

    SQL is based on a relationalprogramming with relation

    SQL manipulates data stor

    about objects and its prop

    SQL concerned about the r

    relation between two obje

    HQL is case sensitive while

    va class name into file name. This translate file na

    java class loader. This addClass function is import

    your code.

    =========================================

    s immutable?

    false.

    =========================================

    rformance in any hibernate application is to emplo

    gement, and Data Caching.

    =========================================

    hibernate?

    =========================================

    nstead of using table-name and property of pojo-cl

    object from DB while SQL use table-name and col

    l database model whereas HQL is a combination ofal database concept.

    d in tables and modifies its rows and columns. HQL

    rties.

    lationship that exists between two tables while H

    ts.

    SQL is not case sensitive.

    e is then loaded

    nt if you want

    ==============

    ==============

    SQL

    ==============

    ==============

    ass instead of

    mn-name.

    object-oriented

    is concerned

    L considers the

  • 8/13/2019 Hibernate One

    13/21

    HQL and SQL both fire que

    objects that are translated

    SQL works with tables and

    HQL works with classes an

    database.

    HQL supports concepts likeeasy-to-learn language tha

    You write database type i

    runtime.

    HQL contains concepts like

    developers.

    HQL result is not plain data

    HQL even returns the child

    In case of HQL, hibernate a

    underlying database.

    ============================

    Difference between HQL and criteri

    HQL is to perform both sel

    selecting the data, we cann

    HQL is suitable for executin

    queries.

    HQL doesnt support pagin

    Criteria used to take more

    With criteria we are safe wi

    as your queries are either fi

    ============================

    What is pagination in hibernate?

    Pagination is used when yo

    record into a single page.

    For convenient and better

    result set is divide into sma

    setFirstResult(int arg0): sets the sta

    setMaxResults(): sets the maximum

    ============================

    ies in a database. In the case of HQL, the queries ar

    to SQL queries in the target database.

    columns to manipulate the data stored in it.

    their properties to finally be mapped to a table str

    polymorphism, inheritance, association, etc. It is amakes SQL object oriented.

    dependent queries in HQL that are converted into

    pagination, dynamic profiling etc. all that are unkn

    but a combination of objects that can be modified

    objects as part of the query result.

    utomatically generates the SQL query and executes

    =========================================

    ia API?

    ct and non-select operations on the data, but crite

    ot perform non-select operations using criteria.

    g static queries, whereas Criteria is suitable for exe

    tion concept, but we can achieve pagination with

    ime to execute then HQL.

    ith SQL injection because of its dynamic query gene

    ixed or parameterized, there is no safe from SQL inj

    =========================================

    u have to display large amount of result. It is tough

    isplay hibernate provides concept of pagination. In

    ll number of pages and at a time you can fetch one

    rting point of your table record.

    result into your single page.

    =========================================

    e in the form of

    ucture in a

    powerful and

    SQL queries at

    wn to SQL

    programmatically.

    it against

    ==============

    ia is only for

    cuting dynamic

    riteria.

    ration but in HQL

    ection.

    ==============

    to display all the

    pagination large

    page.

    ==============

  • 8/13/2019 Hibernate One

    14/21

    Types of inheritance provided by hibernate?

    There are three types of inheritance mapping in hibernate?

    Table per class with unions

    Table per class hierarchy

    Table per subclass

    Example:

    Class Manager and worker are inherited from Employee abstract class.

    Table per concrete class with unions

    In this case there will be 2 tables: Manager and worker [all common attributes will be

    duplicated].

    Table per class hierarchy

    Single table can be mapped to a class hierarchy

    There will be only one table in database called Employee that will represent all the attributes

    required for all 3 classes.

    But it needs some discriminating column to differentiate between Manage and Worker.

    Table per subclass

    In this case there will be 3 tables represent Employee, Manager and Worker. Common attributes

    will not duplicated.

    =====================================================================================

    Types of mapping in hibernate?

    Collection mapping

    Association mapping

    Component mapping

    Collection mapping

    Collection mapping refers to a one-to-many or many-to-mapping relationship which will be

    mapped by using an implementation of java.util.collection.

    Association mapping

    Association mapping refers to a many-to-one or one-to-one relationship which will be mapped

    by using another class which you have mapped in hibernate (also called an entity). The

    association object has its own lifecycle and is simply related to the first object.

    Component mapping

    Component mapping refers to mapping a class (or collection of classes) whole lifecycle is bound

    tightly to the parent. This is also called composition in the strict definition of the word in

  • 8/13/2019 Hibernate One

    15/21

    object-oriented programming. Basically if you delete the parent object the child object should

    also be deleted; it also cannot exist on its own without a parent.

    =====================================================================================

    Difference between NamedNativeQuery and NamedQuery?

    NamedNativeQuery lets you write a named SQL query, while NamedQuery lets you write a

    named HQL query.

    =====================================================================================

    Difference between save and persist method in hibernate?

    Return type of persist method is void while return type of save method is serializable object.

    Persist method and save method both make a transient instance persistent. However, persist

    method doesnt guarantee that the identifier value will be assigned to the persistent instance

    immediately, the assignment might happen at flush time.

    Persist method guarantees that will not execute an INSERT statement if it is called outside oftransaction boundaries. Save method not guarantee the same, it returns an identifier, and if an

    INSERT has to be executed to get the identifier (e.g. identity generator), this INSERT happens

    immediately, no matter if you are inside or outside of a transaction.

    Fourth difference between save and persist method in hibernate is related to previous

    difference on save vs persist. Because of its behavior of persist method outside transaction

    boundary, its useful in long-running conversations with an extended session context. On the

    other hand save method is not good in a long-running conversation with an extended session

    context.

    Save, saveOrUpdate and persist methods are used to save data into database. But save can only

    INSERT records but saveOrUpdate can either INSERT or UPDATE records.

    =====================================================================================

    What is named SQL query in hibernate?

    Named queries are SQL queries which are defined in mapping document using tag

    and called session.getNamedQuery(nameofquery) method.

    Named query allows you to refer a particular query by the name you provided, by the way you

    can define named query in hibernate either by using annotations or xml mapping file, as I said

    above.

    @NameQuery is used to defined single name query and @NameQueries is used to define

    multiple name query hibernate.

    =====================================================================================

    Why its important to provide no argument constructor in hibernate entities?

    Every hibernate entity class must contain a no argument constructor, because hibernate

    framework creates instance of them using reflection API, by calling Class.newInstance() method.

  • 8/13/2019 Hibernate One

    16/21

    This method will throw InstantiationException if it doesnt found no argument constructor inside

    entity class.

    =====================================================================================

    Can we make an entity class final in hibernate?

    Yes, you can make hibernates entity class final, but thats not a good practice. Since hibernate

    uses proxy pattern for performance improvement in case of lazy association, by making an

    entity final, hibernate will no longer be able to use proxy, because java doesnt allow extension

    of final class, thus limiting your performance improvement options. Though, you can avoid this

    penalty, if your persistent class is an implementation of interface, which declares all public

    methods defined in entity class.

    =====================================================================================

    What are extension interfaces?

    When the built-in functionalities provided by hibernate is not sufficient enough, it provides away so that user can include other interfaces and implement those interfaces for user desire

    functionality. These interfaces are called as Extension interfaces.

    =====================================================================================

    What are the extension interfaces that are there in hibernate?

    ProxyFactory interface

    Used to create proxies.

    ConnectionProvider interface

    Used for JDBC connection management.

    TransactionFactory interface

    Used for transaction management.

    Transaction interface

    Used for transaction management.

    TransactionManagementLookup interface

    Used in transaction management.

    Cache interface

    Provides caching techniques and strategies.

    CacheProvider interface

    Same as cache interface.

  • 8/13/2019 Hibernate One

    17/21

    ClassPersister interface

    Provides ORM strategies.

    IdentifierGenerator interface

    Used for primary key gener

    Dialect abstract class

    Provides SQL support

    ============================

    What is meant by method chaining

    Method chaining is a progr

    This is less readable when

    format. Look how a session

    ============================

    What are POJOs?

    POJO stands for plain old java obje

    methods for all the properties thatlogic related to that property.

    ============================

    How does hibernate distinguish bet

    Hibernate uses the version

    If not uses the identifier val

    hibernate managed surrog

    managed by hibernate) sur

    Write your own strategy wi

    ============================

    What is Bag in hibernate?

    A bag is a java collection th

    It allow duplicate values.

    We cannot define primary

    ation.

    =========================================

    ?

    amming technique that is supported by many hiber

    ompared to actual java code. And it is not mandat

    Factory is created when we use method chaining.

    =========================================

    ts. These are just basic JavaBeans that have define

    are there in that bean. Besides they can also have s

    =========================================

    ween transient (i.e. newly created) and detached o

    property, if there is one.

    lue. No identifier value means a new object. This do

    te keys. Does not work for natural keys and assign

    rogate keys.

    th interceptor.isUnsaved().

    =========================================

    at stores elements without caring about the indexi

    eys in bag.

    ==============

    nate interfaces.

    ry to use this

    ==============

    setter and getter

    ome business

    ==============

    bject?

    es work only for

    d (i.e. not

    ==============

    g.

  • 8/13/2019 Hibernate One

    18/21

    =====================================================================================

    Generators in hibernate?

    The following are the list of main generators we are using in the hibernate:

    1. Assigned

    2. Increment

    3. Sequence

    4. Identity

    5. Hilo

    6. Native

    7. Foreign

    8. Uuid.hex

    9. Uuid.string

    In the above generators list, the first 7 are used fro int, long, short types of primary keys, and last 2 are

    used when the primary key column type is string type (varchar2).

    Assigned

    Supported by all database.

    It is default generator which is used by hibernate.

    If generator class is assigned, then the programmer is responsible for assigning the primary key

    value to object which is going to save into the database.

    Increment

    Supported by all databases.

    This generator is used for generating the id value for the new record by using the formula Max

    of id value in Database + 1.

    If we manually assigned the value for primary key for an object, then hibernate doesnt consider

    that value and used max value of id in database + 1 concept only.

    If there is no record initially in the database, then for the first time this will saves primary key

    value as 1.

    Sequence

    Not supported by MySql.

    While inserting a new record in a database, hibernate gets next value from the sequence under

    assigns that value for the new record.

    If programmer has created a sequence in the database then that sequence name should be

    passed as the generator.

    If the programmer has not passed any sequence name, then hibernate creates its own sequence

    with name hibernate-sequence and gets next value from that sequence, and then assigns that

    id value for new record.

    But remember, if hibernate wants to create its own sequence, in hibernate configuration file,

    hbm2ddl.auto property must be set enabled.

  • 8/13/2019 Hibernate One

    19/21

    Example:

    Create sequence MySequence incremented by 5:

    First it will starts with 1 by default.

    Though you send the primary key value.., hibernate uses this sequence concept only.

    But if we not create any sequence, then first 1 and increments by 1 ..bla bla. In this case

    hibernate creating right..? so ensure we have hbm2ddl.auto enabled in the configuration file.

    Identity

    Not supported by oracle.

    In this case the id value is generated by the database, but not by the hibernate, but in case of

    increment hibernate will take over this.

    This identity generator doesnt needs any parameters to pass.

    This identity generator is similar to increment generator, but the difference was increment

    generator is database independent and hibernate uses a select operation for selecting max id

    before inserting new record.

    But in case of identity, no select operation will be generated in order to insert an id value for

    new record by hibernate.

    Hilo

    This generator is database independent.

    For the first record, the id value will be inserted as 1.

    For the second record the id value will be inserted as 2343.

    For the next records the id value will be incremented by 2343 and will stores into the database (I

    mean adds to the previous).

    Actually this hibernate stores the count of id values generated in a column of separated table,

    with name hibernate_unique_key by default with the column name next_hi.

    If we want to modify the table and column names then we need to pass 2 parameters for the

    hilo generators.

    Native

    When we use this generator class, it first checks whether the database supports identity or not,

    if not checks for sequence and if not, then hilo will be used finally the order will be..

    o Identity

    o Sequence

    o hilo

    Example:

    If we are connecting with oracle, if we use generator class as native then it is equal to the generator

    class sequence.

    =====================================================================================

  • 8/13/2019 Hibernate One

    20/21

  • 8/13/2019 Hibernate One

    21/21


Recommended