database and relative
  • Introduction
  • database
  • SQL
  • different kinds of Database
  • JDBC
  • oracle
  • MySQL
  • hibernate1
  • JavaPersistence:HibernateandJPAFundamentals0
  • keys
  • NoSQL DB
Powered by GitBook
On this page
  • 14. Inheritance Mapping and Polymorphic Queries
  • 15. N+1 Selects Problem
  • 16. Batch Fetching
  • 17. Merging Detached Objects
  • 18. Optimistic Locking and Versioning
  • 18.1 Versioning
  • 19. Caching and Object Identity
  • 20. Second-level Caching
  • 20.1 L2 Cache Implementation
  • 20.2 Process Scope Cache & Cluster Scope
  • 20.3 Caching Associations(in Second-level Cache)

Was this helpful?

hibernate1

14. Inheritance Mapping and Polymorphic Queries

Inheritance(SINGLE_TABLE):

Inheritance(JOINED):The superclass has a table and each subclass has a table that contains only un-inherited properties(the subclass tables have a primary key that is a foreign key of the superclass).

Inheritance(TABLE_**PER\_CLASS):**

15. N+1 Selects Problem

N+1 Selects:

1 select for all the parent objects

1 select for each child object(It is the N select, there could be N child object).

Be default, single point associations (@OneToOne and @ManyToOne) are eagerly fetched.

It would hurt the performance and make a huge select statement.

Two way to solve N+1 Selects Problem?

  1. The solution is to switch the fetching strategy of single point associations from eager to Lazy.

  2. Write the query based on the requirements(e.g. using left fetch join to load the child objects eagerly).

16. Batch Fetching

@BatchSize(size=4) //from Hibernate not JPA

Using Batch Fetching, Hibernate can load several uninitialized proxies, even if just one proxy is accessed.

Note: Batch Fetching is an optimization of the Lazy Fetching strategy.

It neither gives us a Huge Select statement nor N+1 Small Select Statement. It gives us a in between solution.

17. Merging Detached Objects

In the different EntityManager, it it the merging detached object.

Guide mergedGuide = entityManager.merge(guide);

so it only merge the guide instance not the student(the associated), even student has been modified.

But after

class Guide
...
@OneToMany(
    mappedBy="guide",
    cascade={CascadeType.MERGE}
)
private Set<Student> students = new HashSet<Student>();
...

The associated student will be merged.

18. Optimistic Locking and Versioning

18.1 Versioning

alter table guide add version int(11) not null default 0;

using @Version in entity

Implementing a business process that spans through multiple transactions should be done using the versioning strategy, to prevent lost updates.

We should always handle exceptions/(transaction failure) in a try/catch block.

OptimisticLockException:

if the entity's version has been changed.Avoid the update missing.

try{
    txn2.begin();
    Guide mergedGuide=em2.merge(guide);
    txn2.commit();
}catch(OptimisticLockException e){
    if(txn2!=null){
    txn2.roolback();
    System.err.println("The guide was updated by some other user while you were doing interesting things.");
    }
}finally{
    if(em2!=null) em2.close();
}

Optimistic Locking: Official name of the Versioning strategy to prevent Lost Updates. No Database Locking.

Use Versioning Strategy(Optimistic Locking) to prevent Lost Updates when implementing a Conversation(Multiple transactions/[request/response cycles]).

Pessimistic Locking(Database Locking) is usable only within a single transaction.

When to use Pessimistic Locking?

When you've got multiple database queries being executed on the same data, within a single transactions.

em.createQuery(....).setLockMode(LockModeType.PESSIMISTIC_READ).getResultList(); //place a read lock on the data being read.
LockModeType.PESSIMISTIC_WRITE//placing a write lock, to modify the data being read.. then update the database

19. Caching and Object Identity

The First-level Cache provide the repeatable_read even the database is in the lower isolation lever on transaction.

20. Second-level Caching

By default, Hibernate does not cache the persistent objects across different EntityManagers.

First Level Cache(scope): EntityManager Second Level Cache(scope): EntityManagerFactory

A cache hit is a state in which data requested for processing by a component or application is found in the cache memory. It is a faster means of delivering data to the processor, as the cache already contains the requested data.

When the object is not in the EntityManager, it would be required from database. Then stores in the first level cache and second level cache(if it is enabled).

Actually, the data stores in the second level cache is Dehydrated format as key value pairs not just object.

e.g.

Guide[2]=>["Ian Lamb", 4000,"2adfs", 1]

Second level cache provides different regions to store different kinds of data:

Entity Data Cache, Collection Cache and Query Result Cache.

20.1 L2 Cache Implementation

Hibernate doesn't provide the L2 cache. There are some cache provider to choose from if the L2 cache is wanted to be used in the application:

EhCache: Single JVM (commonly used)

TreeCache from JBoss: Multiple JVMs

Cache

Supported strategies

HashTable (testing only)

read-only, nontrict read-write, read-write

EHCache

read-only, nontrict read-write, read-write

OSCache

read-only, nontrict read-write, read-write

SwarmCache

read-only, nontrict read-write

JBoss Cache 1.x

read-only, transactional

JBoss Cache 2.x

read-only, transactional

A cache concurrency strategy defines a transaction isolation level for an entry in a cache region.

A Cache concurrency strategy defines a transaction isolation level for an entry in a cache region. The default is READ_WRITE==READ_UNCOMMITTED.

20.2 Process Scope Cache & Cluster Scope

Second-level Cache: Process Scope& Cluster Scope

PROCESS SCOPE

CLUSTER SCOPE

Single JVM

Cluster of JVMs

READ_ONLY, NONSTRIC_READ_WRITE, READ_WRITE

TRANSACTIONAL

EhCache

TreeCache from JBOSS (Replicated Clustered Cache)

20.3 Caching Associations(in Second-level Cache)

By default, associated objects aren't cached.

The second-level caching is enabled not only on the class-by-class basis, but the collection-by-collection basis as well.

the example of using entityManagerFactory

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello-world");
        EntityManager entityManager = emf.createEntityManager();
        EntityTransaction txn = entityManager.getTransaction();
        System.out.println("try open");
        try{
            System.out.println("in try");
            txn.begin();
            System.out.println("txn begin");
            /*
            Message msg = new Message("Hello world with Hibernate as JPA Provider");
            entityManager.persist(msg);
            */
            System.out.println("txn begin2");
            Query query = entityManager.createQuery("select guide from Guide as guide");
            System.out.println("txn begin3");
            List<Guide> names=query.getResultList();

            System.out.println("after listguide");
            for(Guide name:names){
                System.out.println("in guide for");
                System.out.println(name);
            }

            txn.commit();
        }catch(Exception e){
            System.out.println("in catch");
            if(txn!=null){txn.rollback();}
        }finally{
            if(entityManager!=null){entityManager.close();}
        }

example for persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">

    <persistence-unit name="hello-world" transaction-type="RESOURCE_LOCAL">
        <properties>

            <!-- Database connection settings -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/hello-world" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="063374" />

            <!-- SQL dialect -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />

            <!-- Create/update tables automatically using mapping metadata -->
            <property name="hibernate.hbm2ddl.auto" value="update" />

            <!-- Pretty print the SQL in the log file and console -->
            <property name="hibernate.format_sql" value="true" />
        </properties>

    </persistence-unit>
</persistence>
PreviousMySQLNextJavaPersistence:HibernateandJPAFundamentals0

Last updated 5 years ago

Was this helpful?