SlideShare a Scribd company logo
Advanced Hibernate Presented by   Haitham Raik
The persistence lifecycle. The persistence context. Object equality. Flush modes. The persistence manager. Transactions. Contextual session. Concurrency. Caching. Agenda
Bulk and batch operations. Filters. Interceptors. The core event system. Fetching plans. Fetching strategies. Advance query options. ToolSet. Agenda  (cont.)
THE PERSISTENCE LIFECYCLE
The persistence lifecycle get() load() find() list() scroll() Iterate() uniqueResult() Transient Persistent Detached Removed save() saveOrUpdate() merge() persist() evict() close() clear() update() saveOrUpdate() lock() merge() delete()
THE PERSISTENCE CONTEXT
One session has one internal persistence context. It is useful for: Automatic dirty checking. First-level cache. Guarantee a scope of java object identity. The persistence context
Automatic Dirty Check: Dirty object: is a persistence object with modifications that have not yet been propagated to the Database. By default, all columns included in the SQL UPDATE statement. To enable dynamic update/insert use : <class  name = &quot;BlogItem&quot;   table = &quot;BLOG_ITEMS&quot;   dynamic-update = &quot;true&quot;   dynamic-insert = &quot;true&quot;  > </class> The persistence context  (cont.)
Object identity: Persistence object has two identifiers: java identifier (x==y) and Database identifier x.getId().equals(y.getId()). bean.getId() or session.getIdentifier(bean) Scope of object identity  refers to the conditions under which java identity is equivalent to database identity. The persistence context  (cont.)
Session session1 = sessionFactory.openSession(); Transaction tx1 = session1.beginTransaction(); Item a = (Item) session1.get(Item. class ,  new  Long(1234) ); Item b = (Item) session1.get(Item. class ,  new  Long(1234) ); ( a==b )  // True, persistent a and b are identical (a.getId().equals(b.getId()))  // True, match the same record tx1.commit(); session1.close(); // References a and b are now to an object in detached state Session session2 = sessionFactory.openSession(); Transaction tx2 = session2.beginTransaction(); Item c = (Item) session2.get(Item. class ,  new  Long(1234) ); ( a==c )  // False, detached a and persistent c are not identical (a.getId().equals(c.getId()))  // True, match the same record tx2.commit(); session2.close(); The persistence context  (cont.)
What is the size of the following Set object? ... session2.close(); Set allObjects = new HashSet(); allObjects.add(a); allObjects.add(b); allObjects.add(c); Do not treat detached objects as identical in-memory. You need to override the equals() and hashCode() methods The persistence context  (cont.)
OBJECT EQUALITY
database identifier equality : if (this==other) return true; if ( !(other instanceof User) ) return false; final User that = (User) other; return  this.id.equals( that.getId() ) ; All properties equality (except the id and collections): if (this==other) return true; if ( !(other instanceof User) ) return false; final User that = (User) other; if ( !this.getUsername().equals( that.getUsername() ) ) return false; if ( !this.getPassword().equals( that.getPassword() ) ) return false; return true; Object equality
Business key equality: if (this==other) return true; if ( !(other instanceof User) ) return false; final User that = (User) other; return  this.username.equals( that.getUsername() ); Key that would identify our instance in the real world. Immutable attribute. Attribute with UNIQUE constraint. Database identifier for associated object. Any date or time-based attribute. Object equality  (cont.)
FLUSH MODES
Flushing the persistence context Changes made to object aren’t immediately propagated to database ( write-behind ). Flushing occur at the following times: When commit a transaction. Sometimes  before executing a query. Call session.flush() session.setFlushMode() FlushMode.AUTO: the default FlushMode.COMMIT. FlushMode.MANUAL. Flush mode
THE PERSISTENCE MANAGER
Making a transient object persistent: Item item = new Item(); item.setName(&quot;Playstation3 incl. all accessories&quot;); item.setEndDate( ... ); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Serializable itemId = session.save(item); tx.commit(); session.close(); The persistence manager
Retrieving a persistent object: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Item item = (Item) session.load(Item.class, new Long(1234)); // Item item = (Item) session.get(Item.class, new Long(1234)); tx.commit(); session.close(); The persistence manager  (cont.)
Modifying a persistence object Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Item item = (Item) session.get(Item.class, new Long(1234)); item.setDescription(&quot;This Playstation is as good as new!&quot;); tx.commit(); session.close(); The persistence manager  (cont.)
Making a persistent object transient hibernate.use_identifier_rollback Example: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Item item = (Item) session.load(Item.class, new Long(1234)); session.delete(item); tx.commit(); session.close(); The persistence manager  (cont.)
Replicating objects: Session session = sessionFactory1.openSession(); Transaction tx = session.beginTransaction(); Item item = (Item) session.get(Item.class, new Long(1234)); tx.commit(); session.close(); Session session2 = sessionFactory2.openSession(); Transaction tx2 = session2.beginTransaction(); session2.replicate(item, ReplicationMode.LATEST_VERSION); tx2.commit(); session2.close(); ReplicationMode.IGNORE ReplicationMode.OVERWRITE ReplicationMode.EXCEPTION ReplicationMode.LATEST_VERSION The persistence manager  (cont.)
Reattaching a modified detached instance: select-before-update=“true” item.setDescription(...); // Loaded in previous Session Session sessionTwo = sessionFactory.openSession(); Transaction tx = sessionTwo.beginTransaction(); sessionTwo.update(item); item.setEndDate(...); tx.commit(); sessionTwo.close(); The persistence manager  (cont.)
Reattaching an unmodified detached object: Session sessionTwo = sessionFactory.openSession(); Transaction tx = sessionTwo.beginTransaction(); sessionTwo.lock(item, LockMode.NONE); item.setDescription(...); item.setEndDate(...); tx.commit(); sessionTwo.close(); The persistence manager  (cont.)
Making a detached object transient Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.delete(item); tx.commit(); session.close(); The persistence manager  (cont.)
TRANSACTIONS
A tomicity: if one step fails, the whole unit of work must fail. C onsistency: left data in a clean and consistent state after the transactions complete. I solation: a particular transaction should not be visible to other concurrently running transaction. D urability: once the transaction completes, all changes become persistent. Transactions
Transaction demarcation: Is determining the transaction boundaries (the start and the end point) Transaction boundaries can be set either programmatically or declaratively. Transactions  (cont.)
Hibernate Transaction: It is unified. It works in a non-managed plain JDBC environment and in an application server with JTA. Another benefit is tight integration with persistence context.  Transactions  (cont.)
Transactions in JavaSE Hibernate obtains a JDBC connection for each Session Session session = null; Transaction tx = null; try { session = sessionFactory.openSession();  //session is lazy // a conn will obtained only when the trxn begins tx = session.beginTransaction();  // conn.setAutoCommit(false) concludeAuction(session); tx.commit();  // flush and commit (here conn is released) // here you can begin another trxn with the same session } catch (RuntimeException ex) {tx.rollback(); } finally {session.close();}  // release all other resources Transactions  (cont.)
Transactions with JTA hibernate.transaction.factory_class = org. hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class The previous example will work without code changes. In case you want to send a message to queue and then save a record to database within a transaction. Then you need to use JTA interface directly. Transactions  (cont.)
UserTransaction utx = (UserTransaction) new InitialContext() .lookup(&quot;java:comp/UserTransaction&quot;); Session session1 = null; Session session2 = null; try { utx.begin(); session1 = auctionDatabase.openSession(); session2 = billingDatabase.openSession(); concludeAuction(session1); billAuction(session2); session1.flush();  // it’s your responsibility to sync with db session2.flush(); utx.commit(); } catch (RuntimeException ex) {utx.rollback();  // rollback } finally {session1.close();session2.close();  // close } Transactions  (cont.)
Hibernate can sync with database automatically before JTA transaction end using: hibernate.transaction.flush_before_completion Hibernate can close session automatically after JTA transaction end using: hibernate.transaction.auto_close_session To enable CMT with hibernate set the following configuration: hibernate.transaction.factory_class = org. hibernate.transaction.CMTTransactionFactory Transactions  (cont.)
CONTEXTUAL SESSION
session-per-request :   the beginning and end of a session is defined by the duration of a database transaction. SessionFactory.getCurrentSession()  get the current session in specific context. hibernate.current_session_context_class  org.hibernate.context.JTASessionContext  (jta) org.hibernate.context.ThreadLocalSessionContext (thread) commit the transaction will close the session Contextual session
CONCURRENCY
Transaction isolation issues: Lost update: two transactions update the same data without locking. Concurrency
Dirty read: transaction A reads uncommitted data. Concurrency  (cont.)
Unrepeatable read: transaction A executes two non-repeatable reads. Concurrency  (cont.)
Second lost updates problem: Transaction A overwrites changes made by Transaction B. Concurrency  (cont.) Tx B Tx A 4. Commit 6. Commit
Phantom read: transaction A reads new data in the second select. Concurrency  (cont.)
Isolation levels: Read uncommitted:  permits dirty read but not lost updates. Read committed:  permits unrepeatable reads but not dirty reads. Repeatable read:  permits neither unrepeatable reads nor dirty reads. Phantom reads may occur. Serializable:  provides the strictest transaction isolation.  Concurrency  (cont.)
Setting an isolation level: Using hibernate configuration option ( hibernate.connection.isolation ) This option values: 1 – Read uncommitted 2 – Read committed 4 – Repeatable Read 8 – Serializable Concurrency  (cont.)
Pessimistic locking: Item i = (Item) session.get(Item.class, 123); // May be another concurrent trxn changes the price i.setPrice(i.getPrice() - 10); tx.commit(); // will sync with db Concurrency  (cont.) Tx B Tx A 4. Commit 6. Commit
Pessimistic locking: Increase the isolation level. Or use pessimistic lock only for this unit of work Item i = (Item) session.get(Item.class, 123, LockMode.UPGRADE);  i.setPrice(i.getPrice() - 10); tx.commit(); // will sync with db Concurrency  (cont.)
Lock Modes LockMode.NONE LockMode.READ LockMode.UPGRADE LockMode.UPGRADE _NOWAIT LockMode.WRITE LockMode.FORCE Concurrency  (cont.)
CACHING
The cache sits between your application and the database  The cache keeps a representation of current database state close to the application. To avoid a database hit. Types of cache: Transaction scope cache. Process scope cache. Cluster scope cache. Caching
Caching and object identity: Transaction scoped cache: guarantee transaction scoped identity. Process scoped cache: Process-scoped identity (must provide object-level locking). Return by value. Cluster scoped cache: Needs a remote communication therefore it can’t guarantee identity across a cluster. Caching  (cont.)
Do not use process scoped cache in the following: Clustered applications (rather use cluster scoped cache) Shared databases between many java applications. Caching  (cont.)
Good candidate classes for caching are classes that represent: data changes rarely Non-critical data (non-financial data) Data that is local to the application and not shared Caching  (cont.)
Cache concurrency strategies: Transactional Read-write Non-strict read-write Read-only (data will never change) Caching  (cont.)
Second-level cache config: hibernate.cache.provider_class = org.hibernate.cache.EhCacheProvider hibernate.cache.use_second_level_cache = true Controlling hibernate caches programmatically: Session.evict() and Session.clear() SessionFactory.evict() Session.setCacheMode(): CacheMode.NORMAL and CacheMode.IGNORE Caching  (cont.)
BULK AND BATCH OPERATIONS
Updating and deleting objects directly in the database without retrieving objects into memory. Query q = session.createQuery(&quot;update Item i set i.isActive = :isActive&quot;); q.setBoolean(&quot;isActive&quot;, true); int updatedItems = q.executeUpdate();  Bulk and batch operations
insert a new entity from another selected entity. Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); String hqlInsert =  &quot;insert into VIPCustomer (id, name) select c.id, c.name from Customer c where c.balance > 10000&quot;; int createdEntities =  s.createQuery( hqlInsert ).executeUpdate(); tx.commit(); session.close(); Bulk and batch operations  (cont.)
Batches ScrollableResults itemCursor = session.createQuery(&quot;from Item&quot;)   .scroll();  // cursor is a pointer to a rs that stays in DB int count=0; while ( itemCursor.next() ) { Item item = (Item) itemCursor.get(0); modifyItem(item); if ( ++count % 100 == 0 ) { session.flush(); session.clear(); } } tx.commit(); session.close(); Bulk and batch operations  (cont.)
Batches For best performance set the value of  hibernate.jdbc.batch_size  as the size of your procedure batch. Disable the second-level cache for that persistent class.  Bulk and batch operations
FILTERS
Define filter: <filter-def name=&quot;myFilter&quot;> <filter-param name=&quot;myFilterParam&quot; type=&quot;string“ [condtion=“default condtion that applies to many entities”]/> </filter-def> Attach to a class: <class name=&quot;myClass&quot; ...> ... <filter name=&quot;myFilter&quot; condition=&quot;:myFilterParam = MY_FILTERED_COLUMN&quot;/> </class> Filters
Example: <filter name=“userTypeFilter&quot; condition=&quot;:userType = userTypeColumn&quot;/> Enable filter: session.enableFilter(&quot;myFilter&quot;).setParameter(&quot;myFilterParam&quot;, &quot;some-value&quot;); Filters use cases: Security limits. Regional data. Temporal data. Filters  (cont.)
INTERCEPTORS
Write an interceptor: public class AuditLogInterceptor extends EmptyInterceptor { public boolean onSave(…) { } public boolean onUpdate(…) {} public boolean postFlush(Iterator iter) {} … } Interceptors
Enabling the interceptor: AuditLogInterceptor interceptor = new AuditLogInterceptor(); Session session = getSessionFactory().openSession(interceptor); Or set it globally (thread-safe interceptor) Configuration.setInterceptor( new AuditLogInterceptor() ); Interceptors  (cont.)
THE CORE EVENT SYSTEM
The new core engine for hibernate is based on events/listeners model. You can override the default listener and provider your own listener: public class SecurityLoadListener extends DefaultLoadEventListener { public void onLoad(LoadEvent event, LoadEventListener.LoadType loadType) throws HibernateException { super.onLoad(event, loadType); } } The core event system
Enable your listener: <session-factory> ... <event type=&quot;load&quot;> <listener class=“com.b1me. SecurityLoadListener &quot;/> </event> </session-factory> The core event system  (cont.)
FETCHING PLANS
What  part of the persistence object network should be loaded into memory. Hibernate by default loads only the objects you’re querying for. Item item = (Item) session.load(Item.class, new Long(123)); Fetching plans
After initializing the proxy (either by using the get() or by calling one of its properties): Item item = (Item) session.load(Item.class, new Long(123)); // Item item = (Item) session.get(Item.class, new Long(123)); item.getId(); // Initialize the proxy item.getDescription();  Fetching plans  (cont.) In the figure associated proxies are just forign keys in the item’s row
Disabling proxy generation for a particular entity: <class name=&quot;CompanyBean&quot; table=&quot;company&quot;  lazy=&quot;false&quot; > session.load(CompanyBean.class, new Integer(2))  // no proxy Eager loading of assotiations: <class name=&quot;UserBean&quot; table=&quot;user&quot;> <many-to-one name=“address&quot; column=“addId“ class=“Address&quot; not-null=&quot;true&quot; lazy=&quot;false&quot;/> </class> <class name=“CompanyBean&quot; table=“company&quot;> <many-to-one name=“address&quot; column=“addId&quot; class=“Address&quot; not-null=&quot;true&quot; /> </class> Fetching plans  (cont.) User Company Address
FETCHING STRATEGIES
How  an associated objects should be loaded, when the owning entity object is loaded. By default, hibernate fetches associated objects and collections lazily. Item item = (Item) session.get(Item.class, new Long(123)); select item.* from ITEM item where item.ITEM_ID=? If you access any associated proxy, a second SELECT is executed. Fetching strategies
List allItems = session.createCriteria(Item.class).list(); // suppose allItems size is 3 ((Item) allItems.get(0)).getSeller().getName(); ((Item) allItems.get(1)).getSeller().getName(); ((Item) allItems.get(2)).getSeller().getName(); Using lazy loading line 1 will execute: select * from ITEM While lines from 3 to 5 will execute: Line 2: Select * from User where id = ?  Line 3: Select * from User where id = ? Line 4: Select * from User where id = ? This will cause  n+1 selects  problem. Fetching strategies  (cont.)
Batch fetching:  if one proxy must be fetched, go ahead and initialize several in the same SELECT.  Batch fetching is a blind-guess optimization. You make a guess and apply a batch size to your user class mapping file: <class name=&quot;User” table=&quot;USERS”  batch-size=&quot;10&quot; > The resulted  (n/10+1)  SQL statements select * from ITEM select * from USER where id in (?, ?, ?) Fetching strategies  (cont.)
Eager Fetching with join (Try to not use): “ Every time I need an Item, I also need the seller of that item” <class name=&quot;Item&quot; table=&quot;ITEM&quot;> <many-to-one name=&quot;seller” class=&quot;User” column=&quot;SELLER_ID”  fetch=&quot;join&quot; /> </class> The following SQL statement will be executed: select i.*, u.* from ITEM i left outer join USERS u on i.SELLER_ID = u.USER_ID where i.ITEM_ID = ? To control the number of joined tables: hibernate.max_fetch_depth Fetching strategies  (cont.)
ADVANCED QUERY OPTIONS
Setting query hints: setFlushMode(FlushMode.COMMIT) setCacheMode(CacheMode.IGNORE) setReadOnly(true) setTimeout(60) // 1 minute setFetchSize(50) setLockMode(LockMode.UPGRADE) setComment(“My comment …”)/  hibernate.use_sql_comments=true Advanced query
Executing a query List all results (you may use setFetchSize()) List l = query.list() List l = criteria.list() Iterating through the results  Iterator iter = query.iterate() Scrolling with database cursors ScrollableResults c = query.scroll();   ScrollableResults c = criteria.scroll();   Advanced query  (cont.)
Calling SQL functions: Any function that is not defined in the Dialect super class may not portable to other database system. To add SQL function to HQL: Configuration cfg = new Configuration(); cfg.addSqlFunction( &quot;lpad&quot;, new StandardSQLFunction(&quot;lpad&quot;, Hibernate.STRING) ); Advanced query  (cont.)
Projection - HQL: Select u.id, upper(u.name), u.age from User u Select count(distinct u.name) from User u Select u.birthofdate, current_date() from User u where u.birthofdate > current_date() Select new StudentSummary(count(s.id), avg(s.mark)) from Student s Advanced query  (cont.)
Projection - Criteria:  Session.createCriteria(User.class).setProjection(Projections.id()) criteria.setProjection(Projections.projectionList() .add(Projections.id())  // Property.forName(“id”) .add(Projections.property(“name”)) ); criteria.setProjection(Projections.projectionList() .add(Projections.count(“id”)) .add(Property.forName(“mark”).avg().as(“averag”)) ); criteria.setProjection(Projections.projectionList() .add(Projections.count(“id”).as(“size”)) .add(Property.forName(“mark”).avg().as(“averag”))  .setResultTransformer(new AliasToBeanResultTransformer(UserSummary.class)) ) Advanced query  (cont.)
Joining relations and associations: Implicit association joins: Querying components: from User u where u.homeAddress.city = 'Bangkok‘ select distinct u.homeAddress.city from User u Expressing implicit association joins From user where user.company.name = ‘STS’ From user where user.company.country.isoCode = ‘JO’ Select user.company.name from User user Advanced query  (cont.)
Joining relations and associations: Ordinary (explicit) join in the FROM clause -For Restrictions (inner join) Using HQL: from UserBean u  join  u.company c where u.name like '%a%' and  c.name = 'STS‘ Select u from UserBean u  join  u.company c where u.name like '%a%' and c.name = 'STS‘ from UserBean u  join  u.addresses a where u.name like '%a%' and a.city = ‘amman’ Select distinct u from UserBean u  join  u.addresses a where u.name like '%a%' and a.city = ‘amman’ Advanced query  (cont.)
Joining relations and associations: Ordinary (explicit) join in the FROM clause - For Restrictions (inner join) Using Criteria: session.createCriteria(User.class) .add(Restrictions.like(“name”, “%a%”)) . createCriteria (“company”) .add(Restrictions.eq(“name”, “sts”)) Session.createCriteria(User.class) . createAlias (“addresses”, “a”) .add(Restrictions.ilike(“[this.]name”, “%a%”)) .add(Restrictions.eq(“a.city”, “amman”)) . setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) ; Advanced query  (cont.)
Joining relations and associations: Dynamic (Eager) fetching strategies - HQL:   from UserBean u  join fetch  u.company c where u.name like '%a%' and c.name = 'STS’ Select  [DISTINCT]  u from UserBean u  join fetch  u.addresses a where u.name like '%a%' and a.city = ‘amman’ Select  [DISTINCT]  u from UserBean u  left join fetch  u.addresses a where u.name like '%a%' and a.city = ‘amman’ Advanced query  (cont.)
Joining relations and associations: Dynamic (Eager) fetching strategies - Criteria:   Criteria criteira = session.createCriteria(User.class) criteria.createCriteria(“company”) criteria.setFetchMode(“company”,FetchMode.JOIN).add.. criteria .setFetchMode(“addresses”, FetchMode.JOIN) /outer join .add...  // restrictions to the root entity criteira.createAlias(“addresses”, “a”,  CriteriaSpecification.INNER_JOIN ).setFetchMode(“a”, FetchMode.JOIN) criteria.setFetchMode(“addresses”, “a”, FetchMode.JOIN).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) Advanced query  (cont.)
Joining relations and associations: Theta style joins: Is useful when your join condition isn’t a foreign key relationship mapped to a class association from User user, LogRecord log where user.username = log.username Select u from User u, LogRecord l where u.username = l.username Advanced query  (cont.)
Using named query Defining a named query <query name=&quot;findItemsByDescription” cache-mode=&quot;ignore&quot; comment=&quot;My Comment...” fetch-size=&quot;50&quot; read-only=&quot;true&quot; timeout=&quot;60&quot;> <![CDATA[ from Item item where item.description like :desc ]]></query> Calling a named query session.getNamedQuery(&quot;findItemsByDescription&quot;). setString(&quot;desc&quot;, description); Advanced query – HQL  (cont.)
Conjunction &  disjunction session.createCriteria(User.class) .add( Restrictions.or( Restrictions.and( Restrictions.like(&quot;firstname&quot;, &quot;G%&quot;), Restrictions.like(&quot;lastname&quot;, &quot;K%&quot;) ), Restrictions.in(&quot;email&quot;, emails) ) ); Advanced query – Criteria  (cont.)
Conjunction &  disjunction session.createCriteria(User.class) .add( Restrictions.disjunction() .add( Restrictions.conjunction() .add( Restrictions.like(&quot;firstname&quot;, &quot;G%&quot;) ) .add( Restrictions.like(&quot;lastname&quot;, &quot;K%&quot;) ) ) .add( Restrictions.in(&quot;email&quot;, emails) ) ); Advanced query – Criteria  (cont.)
TOOLSET
ToolSet
Advanced Hibernate Thank you
Ad

More Related Content

What's hot (20)

Sustaining Test-Driven Development
Sustaining Test-Driven DevelopmentSustaining Test-Driven Development
Sustaining Test-Driven Development
AgileOnTheBeach
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
Carol McDonald
 
Data in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data EfficientlyData in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data Efficiently
Martin Zapletal
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
vamsi krishna
 
Don't Make Android Bad... Again
Don't Make Android Bad... AgainDon't Make Android Bad... Again
Don't Make Android Bad... Again
Pedro Vicente
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
Tomáš Kypta
 
Jasig Cas High Availability - Yale University
Jasig Cas High Availability -  Yale UniversityJasig Cas High Availability -  Yale University
Jasig Cas High Availability - Yale University
Jasig CAS
 
From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()
José Paumard
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns Reconsidered
Alex Miller
 
The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploits
Priyanka Aash
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
Alex Miller
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
Neera Mital
 
Let's Build A Blockchain... in 40 minutes!
Let's Build A Blockchain... in 40 minutes!Let's Build A Blockchain... in 40 minutes!
Let's Build A Blockchain... in 40 minutes!
Michel Schudel
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»
SpbDotNet Community
 
The Ring programming language version 1.8 book - Part 105 of 202
The Ring programming language version 1.8 book - Part 105 of 202The Ring programming language version 1.8 book - Part 105 of 202
The Ring programming language version 1.8 book - Part 105 of 202
Mahmoud Samir Fayed
 
Java
JavaJava
Java
Frida Herencia Quispe
 
04 threads
04 threads04 threads
04 threads
ambar khetan
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
The zen of async: Best practices for best performance
The zen of async: Best practices for best performanceThe zen of async: Best practices for best performance
The zen of async: Best practices for best performance
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Hithem Ahmed
 
Sustaining Test-Driven Development
Sustaining Test-Driven DevelopmentSustaining Test-Driven Development
Sustaining Test-Driven Development
AgileOnTheBeach
 
Data in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data EfficientlyData in Motion: Streaming Static Data Efficiently
Data in Motion: Streaming Static Data Efficiently
Martin Zapletal
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
vamsi krishna
 
Don't Make Android Bad... Again
Don't Make Android Bad... AgainDon't Make Android Bad... Again
Don't Make Android Bad... Again
Pedro Vicente
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
Tomáš Kypta
 
Jasig Cas High Availability - Yale University
Jasig Cas High Availability -  Yale UniversityJasig Cas High Availability -  Yale University
Jasig Cas High Availability - Yale University
Jasig CAS
 
From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()
José Paumard
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns Reconsidered
Alex Miller
 
The art of reverse engineering flash exploits
The art of reverse engineering flash exploitsThe art of reverse engineering flash exploits
The art of reverse engineering flash exploits
Priyanka Aash
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
Alex Miller
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
Neera Mital
 
Let's Build A Blockchain... in 40 minutes!
Let's Build A Blockchain... in 40 minutes!Let's Build A Blockchain... in 40 minutes!
Let's Build A Blockchain... in 40 minutes!
Michel Schudel
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»
SpbDotNet Community
 
The Ring programming language version 1.8 book - Part 105 of 202
The Ring programming language version 1.8 book - Part 105 of 202The Ring programming language version 1.8 book - Part 105 of 202
The Ring programming language version 1.8 book - Part 105 of 202
Mahmoud Samir Fayed
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 

Viewers also liked (14)

CURRICULUM VITAE
CURRICULUM VITAECURRICULUM VITAE
CURRICULUM VITAE
charles odero matengo
 
Kampanje din optiker sommer 2016
Kampanje din optiker sommer 2016Kampanje din optiker sommer 2016
Kampanje din optiker sommer 2016
zabizabi
 
Las tic
Las ticLas tic
Las tic
Gloria Vega Ceja
 
Aciones para favoreser la salud qywuuey
Aciones para favoreser la salud qywuueyAciones para favoreser la salud qywuuey
Aciones para favoreser la salud qywuuey
Gloria Vega Ceja
 
JA Family Education Day Keynote: The Ups and Downs of Arthritis--How to foste...
JA Family Education Day Keynote: The Ups and Downs of Arthritis--How to foste...JA Family Education Day Keynote: The Ups and Downs of Arthritis--How to foste...
JA Family Education Day Keynote: The Ups and Downs of Arthritis--How to foste...
Arthritis Foundation, Great West Region, San Francisco office
 
Psychology CV Newest
Psychology CV NewestPsychology CV Newest
Psychology CV Newest
Naomi Eastham MBPsS
 
Affecto (kort vers)
Affecto (kort vers)Affecto (kort vers)
Affecto (kort vers)
Kristoffer Lundegren
 
Presentacion Slideshare Xime
Presentacion Slideshare XimePresentacion Slideshare Xime
Presentacion Slideshare Xime
xime_divastar
 
La gatita miedosa
La gatita miedosaLa gatita miedosa
La gatita miedosa
Jhossytorres94
 
Acciones para favorecer la salud 1
Acciones para favorecer   la salud 1Acciones para favorecer   la salud 1
Acciones para favorecer la salud 1
Gloria Vega Ceja
 
Brand Avatars
Brand AvatarsBrand Avatars
Brand Avatars
Vyshnavi Doss
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"
Anna Shymchenko
 
Lead & Arsenic poisoning in America
 Lead & Arsenic poisoning in America Lead & Arsenic poisoning in America
Lead & Arsenic poisoning in America
AMERICANMEDICALDETECTIVE
 
Arduino compatible layer (with 6LoWPAN) on Contiki
Arduino compatible layer (with 6LoWPAN) on ContikiArduino compatible layer (with 6LoWPAN) on Contiki
Arduino compatible layer (with 6LoWPAN) on Contiki
裕士 常田
 
Kampanje din optiker sommer 2016
Kampanje din optiker sommer 2016Kampanje din optiker sommer 2016
Kampanje din optiker sommer 2016
zabizabi
 
Aciones para favoreser la salud qywuuey
Aciones para favoreser la salud qywuueyAciones para favoreser la salud qywuuey
Aciones para favoreser la salud qywuuey
Gloria Vega Ceja
 
Presentacion Slideshare Xime
Presentacion Slideshare XimePresentacion Slideshare Xime
Presentacion Slideshare Xime
xime_divastar
 
Acciones para favorecer la salud 1
Acciones para favorecer   la salud 1Acciones para favorecer   la salud 1
Acciones para favorecer la salud 1
Gloria Vega Ceja
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"
Anna Shymchenko
 
Arduino compatible layer (with 6LoWPAN) on Contiki
Arduino compatible layer (with 6LoWPAN) on ContikiArduino compatible layer (with 6LoWPAN) on Contiki
Arduino compatible layer (with 6LoWPAN) on Contiki
裕士 常田
 
Ad

Similar to Advanced Hibernate (20)

09 Application Design
09 Application Design09 Application Design
09 Application Design
Ranjan Kumar
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
Paco de la Cruz
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in Java
Misha Kozik
 
Jpa buenas practicas
Jpa buenas practicasJpa buenas practicas
Jpa buenas practicas
fernellc
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
명신 김
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
Lluis Franco
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
Paco de la Cruz
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
Simon Su
 
Pharos
PharosPharos
Pharos
SeongHyun Jeong
 
Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !
Mirco Vanini
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
Nguyen Cao
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
Guy Korland
 
Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...
Docker, Inc.
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
Leonid Maslov
 
Using Apache Spark to Solve Sessionization Problem in Batch and Streaming
Using Apache Spark to Solve Sessionization Problem in Batch and StreamingUsing Apache Spark to Solve Sessionization Problem in Batch and Streaming
Using Apache Spark to Solve Sessionization Problem in Batch and Streaming
Databricks
 
Concurrency gotchas
Concurrency gotchasConcurrency gotchas
Concurrency gotchas
Jitender Jain
 
09 Application Design
09 Application Design09 Application Design
09 Application Design
Ranjan Kumar
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
Paco de la Cruz
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in Java
Misha Kozik
 
Jpa buenas practicas
Jpa buenas practicasJpa buenas practicas
Jpa buenas practicas
fernellc
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
명신 김
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
Lluis Franco
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
Paco de la Cruz
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
Simon Su
 
Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !
Mirco Vanini
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
Nguyen Cao
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
Guy Korland
 
Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...Online Meetup: Why should container system / platform builders care about con...
Online Meetup: Why should container system / platform builders care about con...
Docker, Inc.
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
Leonid Maslov
 
Using Apache Spark to Solve Sessionization Problem in Batch and Streaming
Using Apache Spark to Solve Sessionization Problem in Batch and StreamingUsing Apache Spark to Solve Sessionization Problem in Batch and Streaming
Using Apache Spark to Solve Sessionization Problem in Batch and Streaming
Databricks
 
Ad

More from Haitham Raik (11)

History of Software Architecture
History of Software ArchitectureHistory of Software Architecture
History of Software Architecture
Haitham Raik
 
Unified Microservices Patterns List
Unified Microservices Patterns ListUnified Microservices Patterns List
Unified Microservices Patterns List
Haitham Raik
 
GIT In Detail
GIT In DetailGIT In Detail
GIT In Detail
Haitham Raik
 
PCI security requirements secure coding and code review 2014
PCI security requirements   secure coding and code review 2014PCI security requirements   secure coding and code review 2014
PCI security requirements secure coding and code review 2014
Haitham Raik
 
PCI Security Requirements - secure coding
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure coding
Haitham Raik
 
Red hat linux essentials
Red hat linux essentialsRed hat linux essentials
Red hat linux essentials
Haitham Raik
 
Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2
Haitham Raik
 
Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1
Haitham Raik
 
IBM OOAD Part1 Summary
IBM OOAD Part1 SummaryIBM OOAD Part1 Summary
IBM OOAD Part1 Summary
Haitham Raik
 
JEE5 New Features
JEE5 New FeaturesJEE5 New Features
JEE5 New Features
Haitham Raik
 
JMX
JMXJMX
JMX
Haitham Raik
 
History of Software Architecture
History of Software ArchitectureHistory of Software Architecture
History of Software Architecture
Haitham Raik
 
Unified Microservices Patterns List
Unified Microservices Patterns ListUnified Microservices Patterns List
Unified Microservices Patterns List
Haitham Raik
 
PCI security requirements secure coding and code review 2014
PCI security requirements   secure coding and code review 2014PCI security requirements   secure coding and code review 2014
PCI security requirements secure coding and code review 2014
Haitham Raik
 
PCI Security Requirements - secure coding
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure coding
Haitham Raik
 
Red hat linux essentials
Red hat linux essentialsRed hat linux essentials
Red hat linux essentials
Haitham Raik
 
Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2
Haitham Raik
 
Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1
Haitham Raik
 
IBM OOAD Part1 Summary
IBM OOAD Part1 SummaryIBM OOAD Part1 Summary
IBM OOAD Part1 Summary
Haitham Raik
 

Recently uploaded (20)

Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 

Advanced Hibernate

  • 2. The persistence lifecycle. The persistence context. Object equality. Flush modes. The persistence manager. Transactions. Contextual session. Concurrency. Caching. Agenda
  • 3. Bulk and batch operations. Filters. Interceptors. The core event system. Fetching plans. Fetching strategies. Advance query options. ToolSet. Agenda (cont.)
  • 5. The persistence lifecycle get() load() find() list() scroll() Iterate() uniqueResult() Transient Persistent Detached Removed save() saveOrUpdate() merge() persist() evict() close() clear() update() saveOrUpdate() lock() merge() delete()
  • 7. One session has one internal persistence context. It is useful for: Automatic dirty checking. First-level cache. Guarantee a scope of java object identity. The persistence context
  • 8. Automatic Dirty Check: Dirty object: is a persistence object with modifications that have not yet been propagated to the Database. By default, all columns included in the SQL UPDATE statement. To enable dynamic update/insert use : <class name = &quot;BlogItem&quot; table = &quot;BLOG_ITEMS&quot; dynamic-update = &quot;true&quot; dynamic-insert = &quot;true&quot; > </class> The persistence context (cont.)
  • 9. Object identity: Persistence object has two identifiers: java identifier (x==y) and Database identifier x.getId().equals(y.getId()). bean.getId() or session.getIdentifier(bean) Scope of object identity refers to the conditions under which java identity is equivalent to database identity. The persistence context (cont.)
  • 10. Session session1 = sessionFactory.openSession(); Transaction tx1 = session1.beginTransaction(); Item a = (Item) session1.get(Item. class , new Long(1234) ); Item b = (Item) session1.get(Item. class , new Long(1234) ); ( a==b ) // True, persistent a and b are identical (a.getId().equals(b.getId())) // True, match the same record tx1.commit(); session1.close(); // References a and b are now to an object in detached state Session session2 = sessionFactory.openSession(); Transaction tx2 = session2.beginTransaction(); Item c = (Item) session2.get(Item. class , new Long(1234) ); ( a==c ) // False, detached a and persistent c are not identical (a.getId().equals(c.getId())) // True, match the same record tx2.commit(); session2.close(); The persistence context (cont.)
  • 11. What is the size of the following Set object? ... session2.close(); Set allObjects = new HashSet(); allObjects.add(a); allObjects.add(b); allObjects.add(c); Do not treat detached objects as identical in-memory. You need to override the equals() and hashCode() methods The persistence context (cont.)
  • 13. database identifier equality : if (this==other) return true; if ( !(other instanceof User) ) return false; final User that = (User) other; return this.id.equals( that.getId() ) ; All properties equality (except the id and collections): if (this==other) return true; if ( !(other instanceof User) ) return false; final User that = (User) other; if ( !this.getUsername().equals( that.getUsername() ) ) return false; if ( !this.getPassword().equals( that.getPassword() ) ) return false; return true; Object equality
  • 14. Business key equality: if (this==other) return true; if ( !(other instanceof User) ) return false; final User that = (User) other; return this.username.equals( that.getUsername() ); Key that would identify our instance in the real world. Immutable attribute. Attribute with UNIQUE constraint. Database identifier for associated object. Any date or time-based attribute. Object equality (cont.)
  • 16. Flushing the persistence context Changes made to object aren’t immediately propagated to database ( write-behind ). Flushing occur at the following times: When commit a transaction. Sometimes before executing a query. Call session.flush() session.setFlushMode() FlushMode.AUTO: the default FlushMode.COMMIT. FlushMode.MANUAL. Flush mode
  • 18. Making a transient object persistent: Item item = new Item(); item.setName(&quot;Playstation3 incl. all accessories&quot;); item.setEndDate( ... ); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Serializable itemId = session.save(item); tx.commit(); session.close(); The persistence manager
  • 19. Retrieving a persistent object: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Item item = (Item) session.load(Item.class, new Long(1234)); // Item item = (Item) session.get(Item.class, new Long(1234)); tx.commit(); session.close(); The persistence manager (cont.)
  • 20. Modifying a persistence object Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Item item = (Item) session.get(Item.class, new Long(1234)); item.setDescription(&quot;This Playstation is as good as new!&quot;); tx.commit(); session.close(); The persistence manager (cont.)
  • 21. Making a persistent object transient hibernate.use_identifier_rollback Example: Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Item item = (Item) session.load(Item.class, new Long(1234)); session.delete(item); tx.commit(); session.close(); The persistence manager (cont.)
  • 22. Replicating objects: Session session = sessionFactory1.openSession(); Transaction tx = session.beginTransaction(); Item item = (Item) session.get(Item.class, new Long(1234)); tx.commit(); session.close(); Session session2 = sessionFactory2.openSession(); Transaction tx2 = session2.beginTransaction(); session2.replicate(item, ReplicationMode.LATEST_VERSION); tx2.commit(); session2.close(); ReplicationMode.IGNORE ReplicationMode.OVERWRITE ReplicationMode.EXCEPTION ReplicationMode.LATEST_VERSION The persistence manager (cont.)
  • 23. Reattaching a modified detached instance: select-before-update=“true” item.setDescription(...); // Loaded in previous Session Session sessionTwo = sessionFactory.openSession(); Transaction tx = sessionTwo.beginTransaction(); sessionTwo.update(item); item.setEndDate(...); tx.commit(); sessionTwo.close(); The persistence manager (cont.)
  • 24. Reattaching an unmodified detached object: Session sessionTwo = sessionFactory.openSession(); Transaction tx = sessionTwo.beginTransaction(); sessionTwo.lock(item, LockMode.NONE); item.setDescription(...); item.setEndDate(...); tx.commit(); sessionTwo.close(); The persistence manager (cont.)
  • 25. Making a detached object transient Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); session.delete(item); tx.commit(); session.close(); The persistence manager (cont.)
  • 27. A tomicity: if one step fails, the whole unit of work must fail. C onsistency: left data in a clean and consistent state after the transactions complete. I solation: a particular transaction should not be visible to other concurrently running transaction. D urability: once the transaction completes, all changes become persistent. Transactions
  • 28. Transaction demarcation: Is determining the transaction boundaries (the start and the end point) Transaction boundaries can be set either programmatically or declaratively. Transactions (cont.)
  • 29. Hibernate Transaction: It is unified. It works in a non-managed plain JDBC environment and in an application server with JTA. Another benefit is tight integration with persistence context. Transactions (cont.)
  • 30. Transactions in JavaSE Hibernate obtains a JDBC connection for each Session Session session = null; Transaction tx = null; try { session = sessionFactory.openSession(); //session is lazy // a conn will obtained only when the trxn begins tx = session.beginTransaction(); // conn.setAutoCommit(false) concludeAuction(session); tx.commit(); // flush and commit (here conn is released) // here you can begin another trxn with the same session } catch (RuntimeException ex) {tx.rollback(); } finally {session.close();} // release all other resources Transactions (cont.)
  • 31. Transactions with JTA hibernate.transaction.factory_class = org. hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class The previous example will work without code changes. In case you want to send a message to queue and then save a record to database within a transaction. Then you need to use JTA interface directly. Transactions (cont.)
  • 32. UserTransaction utx = (UserTransaction) new InitialContext() .lookup(&quot;java:comp/UserTransaction&quot;); Session session1 = null; Session session2 = null; try { utx.begin(); session1 = auctionDatabase.openSession(); session2 = billingDatabase.openSession(); concludeAuction(session1); billAuction(session2); session1.flush(); // it’s your responsibility to sync with db session2.flush(); utx.commit(); } catch (RuntimeException ex) {utx.rollback(); // rollback } finally {session1.close();session2.close(); // close } Transactions (cont.)
  • 33. Hibernate can sync with database automatically before JTA transaction end using: hibernate.transaction.flush_before_completion Hibernate can close session automatically after JTA transaction end using: hibernate.transaction.auto_close_session To enable CMT with hibernate set the following configuration: hibernate.transaction.factory_class = org. hibernate.transaction.CMTTransactionFactory Transactions (cont.)
  • 35. session-per-request : the beginning and end of a session is defined by the duration of a database transaction. SessionFactory.getCurrentSession() get the current session in specific context. hibernate.current_session_context_class org.hibernate.context.JTASessionContext (jta) org.hibernate.context.ThreadLocalSessionContext (thread) commit the transaction will close the session Contextual session
  • 37. Transaction isolation issues: Lost update: two transactions update the same data without locking. Concurrency
  • 38. Dirty read: transaction A reads uncommitted data. Concurrency (cont.)
  • 39. Unrepeatable read: transaction A executes two non-repeatable reads. Concurrency (cont.)
  • 40. Second lost updates problem: Transaction A overwrites changes made by Transaction B. Concurrency (cont.) Tx B Tx A 4. Commit 6. Commit
  • 41. Phantom read: transaction A reads new data in the second select. Concurrency (cont.)
  • 42. Isolation levels: Read uncommitted: permits dirty read but not lost updates. Read committed: permits unrepeatable reads but not dirty reads. Repeatable read: permits neither unrepeatable reads nor dirty reads. Phantom reads may occur. Serializable: provides the strictest transaction isolation. Concurrency (cont.)
  • 43. Setting an isolation level: Using hibernate configuration option ( hibernate.connection.isolation ) This option values: 1 – Read uncommitted 2 – Read committed 4 – Repeatable Read 8 – Serializable Concurrency (cont.)
  • 44. Pessimistic locking: Item i = (Item) session.get(Item.class, 123); // May be another concurrent trxn changes the price i.setPrice(i.getPrice() - 10); tx.commit(); // will sync with db Concurrency (cont.) Tx B Tx A 4. Commit 6. Commit
  • 45. Pessimistic locking: Increase the isolation level. Or use pessimistic lock only for this unit of work Item i = (Item) session.get(Item.class, 123, LockMode.UPGRADE); i.setPrice(i.getPrice() - 10); tx.commit(); // will sync with db Concurrency (cont.)
  • 46. Lock Modes LockMode.NONE LockMode.READ LockMode.UPGRADE LockMode.UPGRADE _NOWAIT LockMode.WRITE LockMode.FORCE Concurrency (cont.)
  • 48. The cache sits between your application and the database The cache keeps a representation of current database state close to the application. To avoid a database hit. Types of cache: Transaction scope cache. Process scope cache. Cluster scope cache. Caching
  • 49. Caching and object identity: Transaction scoped cache: guarantee transaction scoped identity. Process scoped cache: Process-scoped identity (must provide object-level locking). Return by value. Cluster scoped cache: Needs a remote communication therefore it can’t guarantee identity across a cluster. Caching (cont.)
  • 50. Do not use process scoped cache in the following: Clustered applications (rather use cluster scoped cache) Shared databases between many java applications. Caching (cont.)
  • 51. Good candidate classes for caching are classes that represent: data changes rarely Non-critical data (non-financial data) Data that is local to the application and not shared Caching (cont.)
  • 52. Cache concurrency strategies: Transactional Read-write Non-strict read-write Read-only (data will never change) Caching (cont.)
  • 53. Second-level cache config: hibernate.cache.provider_class = org.hibernate.cache.EhCacheProvider hibernate.cache.use_second_level_cache = true Controlling hibernate caches programmatically: Session.evict() and Session.clear() SessionFactory.evict() Session.setCacheMode(): CacheMode.NORMAL and CacheMode.IGNORE Caching (cont.)
  • 54. BULK AND BATCH OPERATIONS
  • 55. Updating and deleting objects directly in the database without retrieving objects into memory. Query q = session.createQuery(&quot;update Item i set i.isActive = :isActive&quot;); q.setBoolean(&quot;isActive&quot;, true); int updatedItems = q.executeUpdate(); Bulk and batch operations
  • 56. insert a new entity from another selected entity. Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); String hqlInsert = &quot;insert into VIPCustomer (id, name) select c.id, c.name from Customer c where c.balance > 10000&quot;; int createdEntities = s.createQuery( hqlInsert ).executeUpdate(); tx.commit(); session.close(); Bulk and batch operations (cont.)
  • 57. Batches ScrollableResults itemCursor = session.createQuery(&quot;from Item&quot;) .scroll(); // cursor is a pointer to a rs that stays in DB int count=0; while ( itemCursor.next() ) { Item item = (Item) itemCursor.get(0); modifyItem(item); if ( ++count % 100 == 0 ) { session.flush(); session.clear(); } } tx.commit(); session.close(); Bulk and batch operations (cont.)
  • 58. Batches For best performance set the value of hibernate.jdbc.batch_size as the size of your procedure batch. Disable the second-level cache for that persistent class. Bulk and batch operations
  • 60. Define filter: <filter-def name=&quot;myFilter&quot;> <filter-param name=&quot;myFilterParam&quot; type=&quot;string“ [condtion=“default condtion that applies to many entities”]/> </filter-def> Attach to a class: <class name=&quot;myClass&quot; ...> ... <filter name=&quot;myFilter&quot; condition=&quot;:myFilterParam = MY_FILTERED_COLUMN&quot;/> </class> Filters
  • 61. Example: <filter name=“userTypeFilter&quot; condition=&quot;:userType = userTypeColumn&quot;/> Enable filter: session.enableFilter(&quot;myFilter&quot;).setParameter(&quot;myFilterParam&quot;, &quot;some-value&quot;); Filters use cases: Security limits. Regional data. Temporal data. Filters (cont.)
  • 63. Write an interceptor: public class AuditLogInterceptor extends EmptyInterceptor { public boolean onSave(…) { } public boolean onUpdate(…) {} public boolean postFlush(Iterator iter) {} … } Interceptors
  • 64. Enabling the interceptor: AuditLogInterceptor interceptor = new AuditLogInterceptor(); Session session = getSessionFactory().openSession(interceptor); Or set it globally (thread-safe interceptor) Configuration.setInterceptor( new AuditLogInterceptor() ); Interceptors (cont.)
  • 65. THE CORE EVENT SYSTEM
  • 66. The new core engine for hibernate is based on events/listeners model. You can override the default listener and provider your own listener: public class SecurityLoadListener extends DefaultLoadEventListener { public void onLoad(LoadEvent event, LoadEventListener.LoadType loadType) throws HibernateException { super.onLoad(event, loadType); } } The core event system
  • 67. Enable your listener: <session-factory> ... <event type=&quot;load&quot;> <listener class=“com.b1me. SecurityLoadListener &quot;/> </event> </session-factory> The core event system (cont.)
  • 69. What part of the persistence object network should be loaded into memory. Hibernate by default loads only the objects you’re querying for. Item item = (Item) session.load(Item.class, new Long(123)); Fetching plans
  • 70. After initializing the proxy (either by using the get() or by calling one of its properties): Item item = (Item) session.load(Item.class, new Long(123)); // Item item = (Item) session.get(Item.class, new Long(123)); item.getId(); // Initialize the proxy item.getDescription(); Fetching plans (cont.) In the figure associated proxies are just forign keys in the item’s row
  • 71. Disabling proxy generation for a particular entity: <class name=&quot;CompanyBean&quot; table=&quot;company&quot; lazy=&quot;false&quot; > session.load(CompanyBean.class, new Integer(2)) // no proxy Eager loading of assotiations: <class name=&quot;UserBean&quot; table=&quot;user&quot;> <many-to-one name=“address&quot; column=“addId“ class=“Address&quot; not-null=&quot;true&quot; lazy=&quot;false&quot;/> </class> <class name=“CompanyBean&quot; table=“company&quot;> <many-to-one name=“address&quot; column=“addId&quot; class=“Address&quot; not-null=&quot;true&quot; /> </class> Fetching plans (cont.) User Company Address
  • 73. How an associated objects should be loaded, when the owning entity object is loaded. By default, hibernate fetches associated objects and collections lazily. Item item = (Item) session.get(Item.class, new Long(123)); select item.* from ITEM item where item.ITEM_ID=? If you access any associated proxy, a second SELECT is executed. Fetching strategies
  • 74. List allItems = session.createCriteria(Item.class).list(); // suppose allItems size is 3 ((Item) allItems.get(0)).getSeller().getName(); ((Item) allItems.get(1)).getSeller().getName(); ((Item) allItems.get(2)).getSeller().getName(); Using lazy loading line 1 will execute: select * from ITEM While lines from 3 to 5 will execute: Line 2: Select * from User where id = ? Line 3: Select * from User where id = ? Line 4: Select * from User where id = ? This will cause n+1 selects problem. Fetching strategies (cont.)
  • 75. Batch fetching: if one proxy must be fetched, go ahead and initialize several in the same SELECT. Batch fetching is a blind-guess optimization. You make a guess and apply a batch size to your user class mapping file: <class name=&quot;User” table=&quot;USERS” batch-size=&quot;10&quot; > The resulted (n/10+1) SQL statements select * from ITEM select * from USER where id in (?, ?, ?) Fetching strategies (cont.)
  • 76. Eager Fetching with join (Try to not use): “ Every time I need an Item, I also need the seller of that item” <class name=&quot;Item&quot; table=&quot;ITEM&quot;> <many-to-one name=&quot;seller” class=&quot;User” column=&quot;SELLER_ID” fetch=&quot;join&quot; /> </class> The following SQL statement will be executed: select i.*, u.* from ITEM i left outer join USERS u on i.SELLER_ID = u.USER_ID where i.ITEM_ID = ? To control the number of joined tables: hibernate.max_fetch_depth Fetching strategies (cont.)
  • 78. Setting query hints: setFlushMode(FlushMode.COMMIT) setCacheMode(CacheMode.IGNORE) setReadOnly(true) setTimeout(60) // 1 minute setFetchSize(50) setLockMode(LockMode.UPGRADE) setComment(“My comment …”)/ hibernate.use_sql_comments=true Advanced query
  • 79. Executing a query List all results (you may use setFetchSize()) List l = query.list() List l = criteria.list() Iterating through the results Iterator iter = query.iterate() Scrolling with database cursors ScrollableResults c = query.scroll(); ScrollableResults c = criteria.scroll(); Advanced query (cont.)
  • 80. Calling SQL functions: Any function that is not defined in the Dialect super class may not portable to other database system. To add SQL function to HQL: Configuration cfg = new Configuration(); cfg.addSqlFunction( &quot;lpad&quot;, new StandardSQLFunction(&quot;lpad&quot;, Hibernate.STRING) ); Advanced query (cont.)
  • 81. Projection - HQL: Select u.id, upper(u.name), u.age from User u Select count(distinct u.name) from User u Select u.birthofdate, current_date() from User u where u.birthofdate > current_date() Select new StudentSummary(count(s.id), avg(s.mark)) from Student s Advanced query (cont.)
  • 82. Projection - Criteria: Session.createCriteria(User.class).setProjection(Projections.id()) criteria.setProjection(Projections.projectionList() .add(Projections.id()) // Property.forName(“id”) .add(Projections.property(“name”)) ); criteria.setProjection(Projections.projectionList() .add(Projections.count(“id”)) .add(Property.forName(“mark”).avg().as(“averag”)) ); criteria.setProjection(Projections.projectionList() .add(Projections.count(“id”).as(“size”)) .add(Property.forName(“mark”).avg().as(“averag”)) .setResultTransformer(new AliasToBeanResultTransformer(UserSummary.class)) ) Advanced query (cont.)
  • 83. Joining relations and associations: Implicit association joins: Querying components: from User u where u.homeAddress.city = 'Bangkok‘ select distinct u.homeAddress.city from User u Expressing implicit association joins From user where user.company.name = ‘STS’ From user where user.company.country.isoCode = ‘JO’ Select user.company.name from User user Advanced query (cont.)
  • 84. Joining relations and associations: Ordinary (explicit) join in the FROM clause -For Restrictions (inner join) Using HQL: from UserBean u join u.company c where u.name like '%a%' and c.name = 'STS‘ Select u from UserBean u join u.company c where u.name like '%a%' and c.name = 'STS‘ from UserBean u join u.addresses a where u.name like '%a%' and a.city = ‘amman’ Select distinct u from UserBean u join u.addresses a where u.name like '%a%' and a.city = ‘amman’ Advanced query (cont.)
  • 85. Joining relations and associations: Ordinary (explicit) join in the FROM clause - For Restrictions (inner join) Using Criteria: session.createCriteria(User.class) .add(Restrictions.like(“name”, “%a%”)) . createCriteria (“company”) .add(Restrictions.eq(“name”, “sts”)) Session.createCriteria(User.class) . createAlias (“addresses”, “a”) .add(Restrictions.ilike(“[this.]name”, “%a%”)) .add(Restrictions.eq(“a.city”, “amman”)) . setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) ; Advanced query (cont.)
  • 86. Joining relations and associations: Dynamic (Eager) fetching strategies - HQL: from UserBean u join fetch u.company c where u.name like '%a%' and c.name = 'STS’ Select [DISTINCT] u from UserBean u join fetch u.addresses a where u.name like '%a%' and a.city = ‘amman’ Select [DISTINCT] u from UserBean u left join fetch u.addresses a where u.name like '%a%' and a.city = ‘amman’ Advanced query (cont.)
  • 87. Joining relations and associations: Dynamic (Eager) fetching strategies - Criteria: Criteria criteira = session.createCriteria(User.class) criteria.createCriteria(“company”) criteria.setFetchMode(“company”,FetchMode.JOIN).add.. criteria .setFetchMode(“addresses”, FetchMode.JOIN) /outer join .add... // restrictions to the root entity criteira.createAlias(“addresses”, “a”, CriteriaSpecification.INNER_JOIN ).setFetchMode(“a”, FetchMode.JOIN) criteria.setFetchMode(“addresses”, “a”, FetchMode.JOIN).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) Advanced query (cont.)
  • 88. Joining relations and associations: Theta style joins: Is useful when your join condition isn’t a foreign key relationship mapped to a class association from User user, LogRecord log where user.username = log.username Select u from User u, LogRecord l where u.username = l.username Advanced query (cont.)
  • 89. Using named query Defining a named query <query name=&quot;findItemsByDescription” cache-mode=&quot;ignore&quot; comment=&quot;My Comment...” fetch-size=&quot;50&quot; read-only=&quot;true&quot; timeout=&quot;60&quot;> <![CDATA[ from Item item where item.description like :desc ]]></query> Calling a named query session.getNamedQuery(&quot;findItemsByDescription&quot;). setString(&quot;desc&quot;, description); Advanced query – HQL (cont.)
  • 90. Conjunction & disjunction session.createCriteria(User.class) .add( Restrictions.or( Restrictions.and( Restrictions.like(&quot;firstname&quot;, &quot;G%&quot;), Restrictions.like(&quot;lastname&quot;, &quot;K%&quot;) ), Restrictions.in(&quot;email&quot;, emails) ) ); Advanced query – Criteria (cont.)
  • 91. Conjunction & disjunction session.createCriteria(User.class) .add( Restrictions.disjunction() .add( Restrictions.conjunction() .add( Restrictions.like(&quot;firstname&quot;, &quot;G%&quot;) ) .add( Restrictions.like(&quot;lastname&quot;, &quot;K%&quot;) ) ) .add( Restrictions.in(&quot;email&quot;, emails) ) ); Advanced query – Criteria (cont.)

Editor's Notes

  • #6: persistence lifecycle: the states an object goes through during its life However, one of the key factors of your success with Hibernate is your understanding of state management Transient: transient, which means they aren’t associated with any database table row and so their state is lost as soon as they’re no longer referenced by any other object. any modification of a transient instance isn’t known to a persistence context (they are not transactional) Objects that are referenced only by other transient instances are transient. Persistent: An entity instance with a database identity Persistent instances are always associated with a persistence context Detached: detached, indicating that their state is no longer guaranteed to be synchronized with database state (they’re no longer attached to a persistence context) Hibernate offers two operations, reattachment and merging, to reattach .
  • #8: One session has one internal persistence context (it isn’t something you see in your application) It is useful because we can extend it for a long conversation.
  • #9: Automatic dirty check: Hibernate propagates state changes to the database as late as possible but hides this detail from the application (to keep lock times in the Database as short as possible) Hibernate is able to detect exactly which properties have been modified. it’s possible to include only the columns that need updating in the SQL UPDATE (This may bring some performance gains. However, it’s usually not a significant difference and, in theory, could harm performance in some environments). The setting in the class mapping file. We recommend you consider this setting when you have an extraordinarily large number of columns in a table (say, more than 50);
  • #10: Using Database identifier we can know whether two objects match the same record in the database or no. In the most cases the Database identifier is the record primary key The question is it possible to have two different objects match the same record? Or is it always two objects will match two different object. For the scope of object identity we have three common choices: no identity scope: we got the record twice in the same trxn then we will get two different objects if we made two different changes on the two objects. How should we decide which state should be propagated to the Database? session-scoped identity : process scoped identity: one object in the whole JVM. The problem is that we need to synchronize the objects in the multithreaded systems which is expensive.
  • #11: Do not treat detached objects as identical in memory
  • #12: Set does not allow duplicate entries, to determine whether the object is exist or no it uses the equals() The default impl of equals uses the == The Answer: If the equals() method implemented the size is one, otherwise it is two. This can lead to problems if you treat them as equal in detached state.
  • #14: Database identifier can’t be used for transient objects All properties: may cause un equal objects in case two objects from two sessions where one object has been changed
  • #15: Database identifier for associated object: For example, a candidate business key for the Bid class is the identifier of the Item it was made for together with the bid amount. Another example user name and company id as business key for the user
  • #17: Write-behinds usefulness: coalesce many changes into a minimal number of database requests Shorter lock durations inside the database. Take advantage of the JDBC Batch.
  • #19: Persistence manager exposed in many interfaces: Session, Query, Criteria and Transaction Manager services CRUD, Query execution, Trxn mgmt, management of persistence context. SAVE operation: Call to save() does not mean (all the time) an immediate SQL insert stmt execution. That’s depend on the id generator. It’s better to fully initialize the object before managing it with a session.
  • #20: get(): return null if object not exist. Always return object load(): throws ObjectNotFoundException Return proxy (placeholder, wrapper for the id)
  • #21: Here we use the automatic dirty check service to get whether the object changed or no
  • #22: The item object is in removed state after you call delete(); you shouldn’t continue working with it, and, in most cases, you should make sure any reference to it in your application is removed. Do I have to load an object to delete it? Yes, an object has to be loaded into the persistence context; an instance has to be in persistent state to be removed (note that a proxy is good enough). The reason is the interceptors. Otherwise use Bulk operations. hibernate.use_identifier_rollback configuration option: Hibernate sets the database identifier property of the deleted item to null after deletion and flushing. It’s then a clean transient instance.
  • #23: Replication: retrieve objects from one database and store them in another. ■ ReplicationMode.IGNORE —Ignores the object when there is an existing database row with the same identifier in the target database. ■ ReplicationMode.OVERWRITE —Overwrites any existing database row with the same identifier in the target database. ■ ReplicationMode.EXCEPTION —Throws an exception if there is an existing database row with the same identifier in the target database. ■ ReplicationMode.LATEST_VERSION —Overwrites the row in the target database if its version is earlier than the version of the object, or ignores the object otherwise. Requires enabled Hibernate optimistic concurrency control.
  • #24: It doesn’t matter if the item object is modified before or after it’s passed to update() . The important thing here is that the call to update() is reattaching the detached instance to the new Session (and persistence context). Hibernate always treats the object as dirty and schedules an SQL UPDATE ., which will be executed during flush. select-before-update=“true” (mapping config) : Hibernate determines whether the object is dirty by executing a SELECT statement and comparing the object’s current state to the current database state
  • #25: Changes made before the call to lock() aren’t propagated to the database
  • #28: Database transactions have to be short (to keep resources available). In practice, you also need a concept, that allows you to have long-running conversations. Conversations allow the user of your application to have think-time, while still guaranteeing atomic, isolated, and consistent behavior.
  • #29: Hibernate doesn’t roll back in-memory changes to persistent objects
  • #30: The main benefit, however, is tight integration with persistence context management —for example, a Session is flushed automatically when you commit
  • #31: Is it faster to roll back read-only transactions? some developers found this to be faster in some special circumstances The book authors tested this with the more popular database systems and found no difference. And there is no reason why a database system should have a suboptimal implementation No source of real numbers showing a performance difference Always commit your transaction and roll back if the commit fails.
  • #32: manager_lookup_class example: org.hibernate.transaction.JBossTransactionManagerLookup org.hibernate.transaction.WebSphereTransactionManagerLookup
  • #33: It is recommended to use JTA interface directly.
  • #34: If you configure Hibernate to use CMT, it knows that it should flush and close a Session that participates in a system transaction automatically.
  • #36: Using the jta session context if no current session associated with the current JTA transaction one will be started and associated with that transaction. Note that for backwards compatibility, if hibernate.current_session_context_class is not set but a org.hibernate.transaction.TransactionManagerLookup is configured, Hibernate will use the org.hibernate.context.JTASessionContext The Sessions retrieved via getCurrentSession() in &amp;quot;jta&amp;quot; context will be set to automatically flush before the transaction completes, close after the transaction completes, and aggressively release JDBC connections after each statement.
  • #44: These options work in case using JDBC transaction but will not work in case datasource
  • #45: From time to time, it’s useful to specify a more restrictive lock for a particular transaction switching all database connections to a higher isolation level than read committed, but this is a bad default when scalability of the application is a concern. You need better isolation guarantees only for a particular unit of work
  • #46: From time to time, it’s useful to specify a more restrictive lock for a particular transaction switching all database connections to a higher isolation level than read committed, but this is a bad default when scalability of the application is a concern. You need better isolation guarantees only for a particular unit of work
  • #49: Trans action scope cache— Attached to the current unit of work, which may be a database transaction or even a conversation. It’s valid and used only as long as the unit of work runs. Every unit of work has its own cache. Data in this cache isn’t accessed concurrently. ■ Process scope cache— Shared between many (possibly concurrent) units of work or transactions. This means that data in the process scope cache is accessed by concurrently running threads, obviously with implications on transaction isolation. ■ Cluster scope cache— Shared between multiple processes on the same machine or between multiple machines in a cluster. Here, network communication is an important point worth consideration.
  • #50: it’s neither necessary nor desirable to have identical objects in two concurrent threads. Locks held in memory should be avoided for web and enterprise applications. In cluster the communication is required for consistency Process-scoped cache (Return by value used by hibernate as second level cache) Cluster-scoped cache (it might be the second level cache)
  • #53: Transactional—Available in a managed environment only, it guarantees full transactional isolation up to repeatable read, if required. Use this strategy for read-mostly data where it’s critical to prevent stale data in concurrent transactions, in the rare case of an update. Read-write—This strategy maintains read committed isolation, using a timestamping mechanism and is available only in nonclustered environments. Again, use this strategy for read-mostly data where it’s critical to prevent stale data in concurrent transactions, in the rare case if an update. Nonstrict-read-write—Makes no guarantee of consistency between the cache and the database. If there is a possibility of concurrent access to the same entity, you should configure a sufficiently short expiry timeout. Otherwise, you may read stale data from the cache. Use this strategy if data hardly ever changes (many hours, days, or even a week) and a small likelihood of stale data isn’t of critical concern. ■ Read-only—A concurrency strategy suitable for data which never changes. Use it for reference data only.
  • #54: Session.evict(object) to remove an element from the first level cache Session.clear() to remove all items in the first level cache SessionFactory.evict(class) remove from the second level cache all the instances with the same type SessionFactory.evict(class, id) remove the element from the second level cache
  • #57: VIPCustomer must be subclass of Customer.
  • #58: But instead of retrieving the result of the query completely into memory, you open an online cursor. A cursor is a pointer to a result set that stays in the database. To avoid memory exhaustion, you flush() and clear() the persistence context before loading the next 100 objects into it.
  • #59: Note that you should disable the second-level cache for any batch operations; otherwise, each modification of an object during the batch procedure must be propagated to the second-level cache for that persistent class. This is an unnecessary overhead.
  • #61: Filter is an alternative to dynamic database view with dynamic parameterization at runtime. For example, the currently logged-in application user may not have the rights to see everything.
  • #62: Filter is an alternative to dynamic database view with dynamic parameterization at runtime. For example, the currently logged-in application user may not have the rights to see everything.
  • #64: Useful for the audit log of all object modifications Do not use the session in the interceptor rather than use temporary session Interceptor has many other methods. You can use marker interface to mark all classes that should be intercepted. postFlush() is the correct place for logging (auditing) to guarantee the id existence.
  • #68: You can create a stack of listeners
  • #70: The figure: the load does not execute any SQL statement till it is necessary this is opposite to the get() method which always hits the DB. Load returns a proxy Proxies are placeholders that are generated at runtime Proxy is a sub class of the actual bean, so it is required to make all hibernate beans with no private const and no param cons
  • #72: Some times you need to an entity should always be loaded into memory and no place holder should be returned instead. Disabling proxy generation for a particular entity : load() method will try to load the userBean without initialization but when it tries to create company proxy it can’t because it is disabled so it will make an immediate SELECT stmt to fetch both the userBean and companyBean. Some times you want to specify that a particular association should always be loaded
  • #74: The goal of Fetching strategy is to minimize the number of SQL statements and to simplify the SQL statements, so that querying can be as sufficient as possible.
  • #76: In this example: telling Hibernate to pre-fetch up to 10 uninitialized proxies Instead of n+1 selects, you now see n/10+1 selects to retrieve the required collections into memory
  • #77: Obviously, the seller is no longer lazily loaded on demand, but immediately with join. with lazy=&amp;quot;false&amp;quot;, you see an immediate second SELECT With fetch=&amp;quot;join&amp;quot;, you get the seller loaded in the same single SELECT Max fetch depth: Recommended values from 1-5 tables Max fetch depth: 0 will disable join fetching Do not use global fetch join rather than use dynamic fetching
  • #79: FlushMode.COMMIT: does not flush before the query execution (when you don’t need to flush your modifications to the database before executing a query, because conflicting results aren’t a problem) CacheMode.IGNORE: any object retrieved by this query isn’t put in the second-level cache. setReadOnly(): disable the auto-dirty check setTimeout(): long a query is allowed to run by setting a timeout setFetchSize(): can improve data retrieval if you execute a query with list() setLockMode(): pessimistic lock (a lock is held until the end of the database transaction) setComment(): hibernate add your custom comment to each sql stmt it writes to the logs
  • #80: List: One or several SELECT statements are executing immediately, depending on your fetch plan. Iterate Hibernate retrieves only the primary key (identifier) values of entity objects in a first SQL SELECT, and then tries to find the rest of the state of the objects in the persistence context cache, and (if enabled) the second-level cache. Otherwise it will fetch the record using an additional SELECT for each turn. It is effective only if the second level cache enabled for the iterated entity. Otherwise it will execute n+1 problem. Scroll Uses a cursor that is held on the database The cursor points to a particular row in the result of a query, and the application can move the cursor forward and backword. Use it when you need to execute statements that may return too large results that you want to keep at the database level. For example you need all the data but want to retrieve it in several steps. Stop the curose before database transaction.
  • #81: Any function that is called in the WHERE clause of an HQL statement, and that isn’t known to Hibernate, is passed directly to the database, as an SQL function call. You have to register a function in your org.hibernate.Dialect to enable it for the SELECT clause in HQL.
  • #82: These are scalar values, not entity instances. Therefore, they aren’t in any persistent state, like an entity instance would be. They aren’t transactional and obviously aren’t checked automatically for dirty state. The Object[]s returned by this query contain a Long at index 0, a String at index 1, and int at index 2 Demo how to use aggregate functions in the where and select. Demo how to use SQL functions in the where and select. The StudentSummary class is a Java bean, it doesn’t have to be a mapped persistent entity class. On the other hand, if you use the SELECT NEW technique with a mapped entity class, all instances returned by your query are in transient .
  • #83: One property List of properties Aggregation functions Dynamic instantiation
  • #84: Implicit join can be used in many-to-one or one-to-one Demo how to use querying components with where How to use in select
  • #85: you have to assign an alias to a joined association Can be used for restrictions (inner join) Query1: This query returns list of Object[] object[0] is user and object[1] is company Query2: return only list of users rather than pair of users and its company as pair (if you try to access the company from user “user.getCompany()” the company will be loaded lazily). Addresses are not initialized tell they used. And user will be duplicated for each of his addresses Using DISTINCT No duplicates will be returned
  • #86: Inner join createCriteria for *-to-one fetch associated entity eagerly while in associated collections it will be lazy loaded
  • #87: List of users each user has an initialized company Distinct to prevent the duplicate data Uses the outer join Do not use iterate() Do not use setMaxResults In both queries will return list of users and its company in the same query (even if lazy enabled the both entities will be loaded immediately). Don’t fetch more than one collection in parallel (Cartesian product). You can fetch as many single-valued associated objects as you like. Dynamic fetching ignore any fetching strategy you have defined in mapping metadata. Reference duplicate may return, so you can use DISTINCT or Set to remove duplicates.
  • #88: createCriteria for *-to-one fetch associated entity eagerly while in associated collections it will be lazy loaded In case *-to-one by default it will be inner join createCriteria() in case *-to-one fetch eagerly and using inner join In case *-to-one setFetchMode Can be used as createCriteria but you can not add any restrictions on the associated entity In case associated collections I have to use the setFetchMode() to initialize the collection, but it will use the left outer join I have to use the CriteriaSpecification.INNER_JOIN if I want to use the eager fetching with inner join (note there is duplicates) Remove any duplicates
  • #89: The query result consists of ordered pairs
  • #90: Hibernate lets you externalize query strings to the mapping file.
  • #94: FlushMode.COMMIT: does not flush before the query execution (when you don’t need to flush your modifications to the database before executing a query, because conflicting results aren’t a problem) CacheMode.IGNORE: any object retrieved by this query isn’t put in the second-level cache. setReadOnly(): disable the auto-dirty check setTimeout(): long a query is allowed to run by setting a timeout setFetchSize(): can improve data retrieval if you execute a query with list() setLockMode(): pessimistic lock (a lock is held until the end of the database transaction) setComment(): hibernate add your custom comment to each sql stmt it writes to the logs
  翻译: