P. 1
Advanced Hibernate Features

Advanced Hibernate Features

|Views: 358|Likes:
Published by napoleonit76

More info:

Published by: napoleonit76 on Feb 27, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

07/11/2013

pdf

text

original

© 2009 coreservlets.

com

Advanced Hibernate Features
Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/hibernate.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2009 coreservlets.com

For live Spring & Hibernate training, see courses at http://courses.coreservlets.com/. t htt // l t /
Taught by the experts that brought you this tutorial. Available at public venues, or customized versions venues can be held on-site at your organization.
•C Courses d developed and t l d d taught b M t H ll ht by Marty Hall • Courses developed and taught by EE Training: http://courses.coreservlets.com/ Customized Java coreservlets.com experts (edited by Marty)
– Spring, Hibernate/JPA, EJB3, Ruby/Rails – Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics

Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Contact hall@coreservlets.com for details Developed and taught by well-known author and developer. At public venues or onsite at your location.

Topics in This Section p
• • • • • • • • Batch Processing Data Filtering Interceptors and Events Calling Triggers and Stored Procedures 2nd Level Cache Statistics DDL Generation Integration with Spring

4

© 2009 coreservlets.com

Batch P B t h Processing i
Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/hibernate.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Batch Processing g
• When executing operations across large
– A id loading potentially thousands of records into Avoids l di t ti ll th d f d i t memory to perform the exact same action

data sets, it is more optimal to run directly in the database (not in memory)

• In SQL, can be performed with 'Update' and Update 'Delete' commands
– UPDATE ACCOUNT SET BALANCE=BALANCE*1.01; – DELETE FROM ACCOUNT;

Hibernate Batch Update and Delete
• Data is modified directly in the database
– Ch Changes made to d b d database records are NOT reflected in d fl di any in-memory objects – Best to start with a clean persistence context, execute batch update, and THEN load any necessary objects

• Can only be against a single object type • Understands inheritance
– Batch made against a superclass/interface are executed against all subclasses

• B d f lt does not affect any versioning By default, d t ff t i i columns (update only)
– Can execute in a fashion to update version numbers
• 'versioned' keyword

accountType='SAVINGS' // return number of objects updated int updatedItems = q.createQuery( "delete from Account"). .Hibernate Batch Update p // Provide the monthly interest // to savings accounts t i t Query q = session. Hibernate Batch Delete // Provide the monthly interest // to savings accounts t i t Query q = session.executeUpdate().executeUpdate(). // return number of objects deleted // across all subclasses int deletedItems = q.createQuery( "update [versioned] Account set balance= (balance + (balance*interestRate)) where accountType 'SAVINGS' ").

. a balance a accountId a creationDate a.createQuery( "insert into ArchivedAccount( accountId. copied record will start at zero if version column not included in select statement Hibernate Batch Insert // Archive all existing accounts Query q = session.balance from Account a"). creationDate. balance) select a. and its own table Contains all the identical attributes of the Account class Can obtain the ID from the copied object If using versioning. a.creationDate.executeUpdate().Hibernate Batch Inserts • Copy objects from one table to another – Still modified directly in the database • Transfer object needs to be a concrete classes – No superclasses or interfaces • Create a new object and mapping file to transfer the records – Example • ArchivedAccount – – – – Has its own mapping file. int createdObjects = q.accountId.

JSF/MyFaces/Facelets. Struts. Spring.com/ Servlets. Developed and taught by well-known author and developer. Hibernate/JPA. GWT.html Customized Java EE Training: http://courses.coreservlets. JSP.com Data Filtering D t Filt i Originals of Slides and Source Code for Examples: http://courses.© 2009 coreservlets.coreservlets. Ajax. At public venues or onsite at your location.com/Course-Materials/hibernate. Data Filtering g • Limit the amount of data visible without modifying query parameters • Often used for security purposes – Users often only have access to certain levels of information • Si il to label security in the Similar t l b l it i th database . Java 5 & 6.

Define the filter within the mapping file of the targeted entity h d i • Identify the attributes to filter on. appropriate filter. and their types 2.Account" table= ACCOUNT > table="ACCOUNT"> <id name="accountId" column="ACCOUNT_ID"> <generator class="native" /> </id> . After obtaining a session with which to p perform your actions.. 2 Apply the filter on the desired class or collection by indicating it within the <class> or <collection-type> tags <collection type> 3. enable the y .Setting up Data Filters g p 1.vo. <filter name="creationDateFilter" condition="CREATION_DATE > :asOfDate"/> </class> <filter-def name="creationDateFilter"> <filter-param name="asOfDate" type="date" /> </filter def> </filter-def> . setting any applicable parameters Account Class Filter <class name="courses..hibernate.

vo.getAccounts().getSessionFactory().. List accounts = accountService.getCurrentSession(). session.setParameter("asOfDate". session.assertEquals(5.12.08))..disableFilter("creationDateFilter"). Assert. <set name="accountTransactions" inverse="true"> <key column="ACCOUNT_ID" not-null="true"/> <one to many <one-to-many class="courses.enableFilter("creationDateFilter") i bl Filt (" ti D t Filt ") .vo. accounts. accounts. new Date(2008. Assert.Account" table="ACCOUNT"> <id name="accountId" column="ACCOUNT_ID"> <generator class="native" /> </id> .hibernate.Account Class Filter Test Session session = HibernateUtil .size()).hibernate.size()). Account Collection Filter <class name="courses.beginTransaction(). accounts = accountService.assertEquals(2. session.AccountTransaction"/> <filter name="transactionDateFilter" condition="TXDATE > :asOfDate" /> </set> </class> <filter-def <filter def name="transactionDateFilter"> <filter-param name="asOfDate" type="date" /> </filter-def> .getAccounts().

new Date(2008. accountTransactions. Hibernate/JPA. JSP.setParameter("asOfDaate".disableFilter("transactionDateFilter").com/ Servlets.coreservlets.Account Collection Filter Test session.enableFilter("transactionDateFilter") . session. Struts. Developed and taught by well-known author and developer.assertEquals(3. SortedSet accountTransactions = account.getAccountTransactions(). Assert. // Need to evict object from cache! session. Assert assertEquals(3 accountTransactions2 size()).setParameter( asOfDaate . Assert. Ajax.getAccountTransactions().assertEquals(2. . Spring. accountTransactions = account.size()).coreservlets.com/Course-Materials/hibernate.size()). © 2009 coreservlets.html Customized Java EE Training: http://courses.08)). Java 5 & 6.evict(account). GWT. At public venues or onsite at your location.12. accountTransactions2.com Interceptors and Events Originals of Slides and Source Code for Examples: http://courses. JSF/MyFaces/Facelets. .

openSession(Interceptor) – SessionFactory-scoped SessionFactory scoped • Registered on the configuration during factory creation • Applies to all sessions . updated. • Implemented one of two ways – Implement Interceptor directly – E t d EmptyInterceptor (preferred) Extend E t I t t ( f d) • Comes in two flavors – Session-scoped p • Specified when a session is opened • SessionFactory.Interceptors and Events p • Callbacks that fire based on actions of a processing request • Assists with separation of concerns – “Non business” processing “Non-business” • Auditing/logging Interceptors p • Callbacks from the session allowing the application to inspect and/or manipulate properties of a persistent object – Before it is saved. p . deleted or loaded .

6. String[] propertyNames. Type[] types) { propertyNames if (entity instanceof Account) { for (int i = 0. i < propertyNames. Implement the desired callback methods 1. Object[] state. Serializable id.. } } . } } } return false. 4 5. i++) { ( . Configure the interceptor use Account Date Interceptor p public class AccountDateInterceptor extends EmptyInterceptor { public boolean onSave(Object entity. 2. • • afterTransactionBegin(…) afterTransactionCompletion (…) f T i C l i ( ) onSave (…) preFlush(…) preFlush( ) postFlush(…) etc.. p p y g .equalsIgnoreCase("creationDate")) { state[i] = new Date(). 4. return true.length. ) if (propertyNames[i] . Extend the EmptyInterceptor class 2. Either during factory creation After obtaining a session 3.Creating Interceptors g p 1. 2 3.

setInterceptor( new AccountDateInterceptor()) . Events • Can be used in addition to/or replacement of interceptors • Triggered by extending default Hibernate implementations or implementing interfaces DEFAULT LISTENERS DefaultDeleteEventListener DefaultEvictEventListener DefaultLoadEventListener DefaultLockEventListener D f l L kE Li DefaultMergeEventListener DefaultPersistEventListener DefaultSaveOrUpdateEventListener etc.openSession(new AccountDateInterceptor()).configure(). p ( p ()).buildSessionFactory(). // causes interception on ALL sessions i t ti i SessionFactory sessionFactory = Configuration()..Setting an Interceptor g p // when creating the SessionFactory. INTERFACES DeleteEventListener EvictEventListener LoadEventListener LockEventListener L kE Li MergeEventListener PersistEventListener SaveOrUpdateEventListener etc… . ___________________________________________ // set when opening an individual session Session session = HibernateUtil..getSessionFactory() .

getObject() instanceof AccountTransaction) { // if it’s an accountTransaction. ( ()).xml hibernate cfg ml • If not extending.setTransactionDate(new Date()). at.cfg. } } } . Create a listener class in one of two ways • Implementing the desired Hibernate listener interface • Extending an already existing Hibernate default listener li t 2. set t e date t s a accou t a sact o .getObject(). also list the default Hibernate event listener • Hibernate uses these too! Implementing a Listener p g public class AccountTransactionDateEventListener implements SaveOrUpdateEventListener { // this method gets fired on a save or update public void onSaveOrUpdate(SaveOrUpdateEvent saveOrUpdateEvent) throws HibernateException { // check the object type passed in on the event if (saveOrUpdateEvent.Creating Events g 1. the AccountTransaction at = (AccountTransaction) saveOrUpdateEvent. List the listener class in the hibernate.

getObject().event.hibernate.onSaveOrUpdate(saveOrUpdateEvent)..util .def .hibernate.Configure the SessionFactory g y <hibernate-configuration> <session-factory> i f t .AccountTransactionDateEventListener"/> <listener class="org.DefaultSaveOrUpdateEventListener"/> </event> </session-factory> </hibernate-configuration> Extending an Existing Listener g g public class AccountTransactionDateEventListener p extends DefaultSaveOrUpdateEventListener { // this method gets fired on a save or update public void onSaveOrUpdate(SaveOrUpdateEvent saveOrUpdateEvent) throws HibernateException { d h ib i // check the object type passed in on the event if (saveOrUpdateEvent.getObject() instanceof AccountTransaction) { // if it’s an accountTransaction. } super. } } . <event type="save-update"> <listener class="courses. at.setTransactionDate(new Date()).. set the date ( ) AccountTransaction at = (AccountTransaction) saveOrUpdateEvent.

GWT.coreservlets.. JSF/MyFaces/Facelets.com/ Servlets. Spring.. .html Customized Java EE Training: http://courses.hibernate. Developed and taught by well-known author and developer.util .Configure the SessionFactory g y <hibernate-configuration> <session-factory> i f t . JSP. At public venues or onsite at your location.coreservlets.com/Course-Materials/hibernate. Ajax. <event type="save-update"> <listener class="courses. Hibernate/JPA.AccountTransactionDateEventListener"/> </event> </session-factory> </hibernate-configuration> © 2009 coreservlets. Struts.com Calling Triggers and Stored Procedures Originals of Slides and Source Code for Examples: http://courses. Java 5 & 6.

Triggers and Stored Procedures • Leveraging triggers in your database happens outside of Hibernate’s h t id f Hib t ’ knowledge – Sets data on rows after Hibernate actions – Need to be able to obtain those set values • Call database stored procedures through Hibernate code • Setup stored procedures as Hibernate’s Hibernate s way of executing normal processes Triggers gg • Identify columns that are modified automatically by the database in the t ti ll b th d t b i th object mapping file – generated="insert | always“ generated= insert always – Also need to tell Hibernate NOT to insert or p . after insert or update statements . Hibernate will re-read the d t b Hib t ill d th object as appropriate –F i For insert. after the insert statement is executed t ft th i t t t ti t d – For always. as appropriate • If an entity possesses columns identified to be populated by the database. pp p update these columns.

.vo. or delete.. .. <!-.hibernate. p .Causes a re-fetch upon insertion and update --> <property name="updateDate" column="UPDATE_DATE" type="timestamp" insert="false" update="false" generated="always" /> . update. inside the class tag – Overrides the default implementation for those events – Column order is random and unintuitive • Documentation says to look at the SQL log output to see what order Hibernate lists the columns • Must set the ‘callable’ attribute . can set an alias and return type • For insert.EBill" table="EBILL"> ..Setting up Triggers g p gg <class name="courses. similiar syntax and process as named sql-query d l – Defined inside or outside the class tags in the mapping file – If returning a value. </class> Calling Stored Procedures g • For querying.Causes a re-fetch upon insertion --> <property name="creationDate" column="CREATION_DATE" type= timestamp type="timestamp" insert="false" update="false" generated insert generated="insert" /> <!-. must be defined .

Developed and taught by well-known author and developer. Struts. JSF/MyFaces/Facelets. ?)} create ebill(?.html Customized Java EE Training: http://courses. </sql-insert> </class> <!-. ?.coreservlets. Hibernate/JPA..Stored Procedure Setup p <class name="courses.. ?. ?.vo. ?. .com/Course-Materials/hibernate. At public venues or onsite at your location. ?.?.vo. but with callable and return value set --> sq que y a e get b s ca ab e t ue <sql-query name="getEbills" callable="true"> <return alias="ebill" class="courses.Calling procedure to execute the insert --> <sql-insert callable="true" check="param"> {call create_ebill(?.named SQL query.hibernate.com/ Servlets.hibernate. GWT. <!-. Ajax. ?. JSP.coreservlets. ?.EBill"/> { ? = call get_ebills() } g _ () </sql-query> © 2009 coreservlets. Java 5 & 6. ?. Spring.com 2nd L Level Cache lC h Originals of Slides and Source Code for Examples: http://courses.EBill" table="EBILL"> .

replicated clustering .2nd Level Cache • Performance increase for objects with a much greater READ to WRITE ratio j • Great for reference or immutable objects • Not advised for – Frequently changing data q y g g – Tables accessed from other applications • Requires a cache strategy and pluggable cache provider Setting up Caching g p g • Four caching strategies. • Use if the data never changes • Four cache providers are built into Hibernate – – – – EHCache: Simple process scope cache in a single JVM OSCache: Richer set of expiration policies and support SwarmCache: Cluster cache. but most risk free – Read-write – Nonstrict-read-write – Read-only y • Fastest performance. but most risky. but doesn t suppor ‘Query Cache cache doesn’t Query Cache’ JBoss Cache: Fully transactional. each level increases performance and risk of stale data – Transactional • Slowest of caching.

setup special rules for Account objects --> <cache name="courses.EhCacheProvider </property> <property name="cache.tmpdir /> path="java io tmpdir" <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds= 120 timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /> <!-. <property name="cache.use_second_level_cache"> true </property> .Account" a e e ts e o y 000 maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="false" /> </encache> Configuring Hibernate Cache g g <session-factory> .io.provider_class"> org..hibernate.cache..vo. </session-factory> .ehcache.xml <ehcache> <diskStore path= java.hibernate...

Spring.Account" table= ACCOUNT > table="ACCOUNT"> <cache usage="read-write" /> <id name="accountId" column="ACCOUNT_ID"> <generator class= native /> class="native" </id> <discriminator column="ACCOUNT_TYPE" type="string" /> <version name version column="VERSION" name="version" column VERSION type="long" access="field" /> <property name="creationDate" column="CREATION_DATE" type t esta p type="timestamp" update="false" /> update a se / . JSP.html Customized Java EE Training: http://courses.com Statistics St ti ti Originals of Slides and Source Code for Examples: http://courses. Developed and taught by well-known author and developer.hibernate. Struts.Account Mapping File pp g <class name="courses.coreservlets..vo. Java 5 & 6. . </class> © 2009 coreservlets. At public venues or onsite at your location. Hibernate/JPA.com/ Servlets. GWT. Ajax.. JSF/MyFaces/Facelets.com/Course-Materials/hibernate.coreservlets.

testCase. } .logSummary().getStatistics(). testCase. l EntityStatistics accountStats = stats.getEntityStatistics( "courses. testCase.testUpdateAccountBalance().testCreateAccount(). testCase testDeleteAccount().vo. AccountServiceTest testCase = new AccountServiceTest().Example p public static void main(String args[]) { Statistics stats = HibernateUtil. stats. testCase.generate_statistics=true • Can be leveraged to determine usage p patterns and better optimize performance p p • Hibernate Interfaces – Statistics for global information – EntityStatistics for info on Object Type – QueryStatistics for SQL and HQL queries Hibernate Statistics .getSessionFactory().setStatisticsEnabled(true).testGetAccount().Hibernate Statistics • Hibernate maintains statistics on which objects were queried.testDeleteAccount().Account"). stats. and how often bj i d dh f – Enable statistics in the configuration file • hibernate generate statistics=true hibernate.hibernate.

hibernate.StatisticsImpl .stat.stat.collections fetched (minimize this): 8 2594 [main] INFO org.stat.hibernate.hibernate.max query time: 0ms © 2009 coreservlets.hibernate.StatisticsImpl .hibernate.StatisticsImpl .stat.Logging statistics.StatisticsImpl .stat. Java 5 & 6.connections obtained: 10 2578 [main] INFO org.StatisticsImpl 2594 [main] INFO org.StatisticsImpl .hibernate.stat.stat.StatisticsImpl .hibernate. Ajax.hibernate.hibernate.html Customized Java EE Training: http://courses.hibernate.hibernate.stat.stat.hibernate.stat.StatisticsImpl .Hibernate Statistics Output p 2562 [main] INFO org. Spring.stat..stat.hibernate.coreservlets.query cache hits: 0 [main] hib t t t St ti ti I l h hit 2594 [main] INFO org.hibernate.hibernate.StatisticsImpl .StatisticsImpl .StatisticsImpl .stat.hibernate.sessions closed: 20 2562 [main] INFO org.com DDL G Generation ti Originals of Slides and Source Code for Examples: http://courses.collections updated: 0 org.second level cache misses: 1 2578 [main] INFO org hibernate stat StatisticsImpl .stat.entities loaded: 0 org.stat.hibernate.StatisticsImpl . JSP.collections recreated: 12 2594 [main] INFO org.stat.StatisticsImpl . Developed and taught by well-known author and developer.query cache misses: 0 2594 [main] INFO org.collections removed: 12 2594 [main] INFO org.hibernate.optimistic lock failures: 0 2562 [main] INFO org.collections loaded: 8 2594 [main] INFO org hibernate stat StatisticsImpl .entities updated: 1 2594 [main] INFO org.hibernate.hibernate.StatisticsImpl .hibernate.StatisticsImpl .coreservlets.stat.StatisticsImpl .StatisticsImpl .StatisticsImpl .com/ Servlets. JSF/MyFaces/Facelets.stat..entities fetched (minimize this): 0 2594 [main] INFO org.hibernate.flushes: 9 2578 [main] INFO org.sessions opened: 20 [ ] g p p 2562 [main] INFO org. 2562 [main] INFO org.start time: 1228714626244 2562 [main] INFO org.hibernate.StatisticsImpl .StatisticsImpl .hibernate.stat. At public venues or onsite at your location.StatisticsImpl .statements prepared: 22 2578 [main] INFO org.StatisticsImpl .stat.transactions: 10 2562 [main] INFO org.com/Course-Materials/hibernate.stat.entities inserted: 4 2594 [main] INFO org. GWT.StatisticsImpl .StatisticsImpl 2594 [main] INFO org.hibernate.statements closed: 22 2578 [main] INFO org.stat.hibernate.query cache puts: 0 2594 [ i ] INFO org.stat.second level cache puts: 5 2578 [main] INFO org. Struts.successful transactions: 10 2562 [main] INFO org.stat.stat. .StatisticsImpl .entities deleted: 4 2594 [main] INFO org.hibernate.stat.stat.hibernate.StatisticsImpl .StatisticsImpl .stat.queries executed to database: 0 2594 [main] INFO org.StatisticsImpl .StatisticsImpl .. Hibernate/JPA.stat.hibernate.second level cache hits: 2 2578 [main] INFO org.

hbm2ddl.xml file --> <session-factory> <property name="hibernate. • hbm2ddl g • Used through ANT tasks or with Hibernate configuration Hibernate Configuration g <!-. S SchemaUpdate schemaUpdate = p p new SchemaUpdate(cfg). schemaUpdate.DDL Generation • Hibernate provides a tool to automatically generate database objects based on a domain model.cfg.auto"> create|create-drop </property> . or a domain model based on an already existing database.execute()..configure().in the Hiberante. </sessionFactory> __________________________________________________________________________________________ // programmatically Configuration cfg = new Configuration(). ..

com Hibernate and The Spring Framework Originals of Slides and Source Code for Examples: http://courses. Developed and taught by well-known author and developer. JSP.com/ Servlets. Spring Integration p g g • First rate support for Hibernate – Many IOC convenience features • Basic setup – Configure a Spring data source (as normal) – Configure a PropertiesFactoryBean to setup the Hibernate properties – Configure a Spring LocalSessionFactoryBean to wrap th Hibernate SessionFactory the Hib t S i F t – Setup Transaction Management .© 2009 coreservlets. Spring. Hibernate/JPA. Java 5 & 6. At public venues or onsite at your location.html Customized Java EE Training: http://courses.coreservlets. Ajax. GWT.coreservlets. JSF/MyFaces/Facelets. Struts.com/Course-Materials/hibernate.

PropertiesFactoryBean"> <property name="properties"> <props> <prop key="dialect"> org.Oracle10gDialect </prop> <prop key="connection.driver.springframework j g .pool_size">1</prop> <prop key="show_sql">true</prop> <prop key= format_sql >false</prop> key="format sql">false</prop> <prop key="current_session_context_class"> thread </prop> <prop key="hibernate.Spring Data Source p g <bean id="dataSource" class="org.OracleDriver</value> </property> / t <property name="url"> <value> jdbc:oracle:thin:@localhost:1521:XE </value> </property> <property name="username"> <value>lecture9</value> </property> <property name="password"> <value>lecture9</value> </property> </bean> Spring PropertiesFactoryBean p g p y <bean id="hibernateProperties" class="org.hibernate.beans.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.factory_class"> < k "hib t t ti f t l "> org.config.jdbc.factory.springframework .transaction.dialect.transaction.JDBCTransactionFactory </prop> </props> </property> </bean> .hibernate.datasource.

hibernate3.springframework g p g .LocalSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource" /> References the previously defined data source </property> <property name="hibernateProperties"> <ref bean="hibernateProperties" /> </property> <property name="mappingResources"> <list> <value>Account..xml</value> < l >A t hb l</ l > .Hibernate Session Factory y <bean id="sessionFactory" class="org..hbm..orm... References the previously defined </list> PropertiesFactoryBean with the p y </property> defined hibernate properties </bean> List the mapping files Add Transaction Management g • Allow Hibernate to delegate transaction management to the Spring container – Declarative transactions • To setup: – Configure a HibernateTransactionManager in Spring – Create DAO and service implementations that perform the business functionality – S t a TransactionProxyFactoryBean to wrap Setup T ti P F t B t the service target implementation .

HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> Previously defined SessionFactory is injected into the Spring HibernateTransactionManager AccountService Target Class g • Define the DAO and service implementations.Hibernate Transaction Manager g <bean id="txManager" class="org. l i f k hibernate.service. and inject the DAO into the service <bean id="accountDAO" class= courses.orm.springframework.dao.hibernate.hibernate .AccountService"> <property name="accountDAO"> <ref bean="accountDAO" /> </property> </bean> .AccountDAO > class="courses hibernate dao AccountDAO"> <constructor-arg ref="sessionFactory" /> </bean> <bean id="accountServiceTarget" class="courses.

transaction.AccountService Transaction Proxy <bean id="accountService" class="org.. } .interceptor.springframework . i F t i F t public AccountDAO(SessionFactory factory) { sessionFactory = factory.getCurrentSession(). S i F t iis automatically SessionFactory t ti ll injected into the AccountDAO } during construction // excluding try/catch for space purposes public void saveAccount(Account account) { Session session = sessionFactory.TransactionProxyFactoryBean > transaction interceptor TransactionProxyFactoryBean"> <property name="transactionManager"> <ref local= txManager /> local="txManager" Provide the Service Proxy with the previously </property> defined ‘transactionManager’ and <property name="target"> ‘accountServiceTarget’ implementations <ref local accountServiceTarget /> local="accountServiceTarget" </property> <property name="transactionAttributes"> p ops <props> <prop key="*">PROPAGATION_REQUIRED</prop> </props> p p y </property> ‘Declare’ the methods as requiring </bean> transaction management AccountDAO public class AccountDAO { private S i t SessionFactory sessionFactory. } ..

.com/ Servlets. AccountService accountService = (AccountOwnerService) beanFactory. GWT. Ajax.Spring Test Case p g ClassPathResource resource = new ClassPathResource("applicationContext.com Wrap-up Customized Java EE Training: http://courses. // wrapped in a declared transaction accountService.. .. JSP. Struts. At public venues or onsite at your location. // create a new account .. Cl P thR (" li ti C t t l") beanFactory = new XmlBeanFactory(resource). JSF/MyFaces/Facelets.xml"). Java 5 & 6. .coreservlets.saveOrUpdateAccount(account). beanFactory getBean("accountService"). Hibernate/JPA. Developed and taught by well-known author and developer. © 2009 coreservlets. Spring.getBean( accountService ).

we covered a TON of advanced features • Batch Processing • Data Filtering • Great for changing many records in the same fashion • Restrict data.Summary y • In this lecture. possibly for security reasons • Separation of concerns • Interceptors and Events • 2nd Level C h L l Cache • Calling Triggers and Stored Procedures • Statistics • Also for optimization • When the database possesses its own functionality • DDL G Generation i • See how we’re doing – is this really buying us anything? • Let Hibernate create and drop our tables • Integration with Spring • Setting up configuration and injecting SessionFactory • Declarative Transactions Preview of Next Sections • Java Persistence API 63 .

GWT.© 2009 coreservlets. Java 5 & 6. Ajax. At public venues or onsite at your location. Spring.com/ Servlets. JSF/MyFaces/Facelets. Developed and taught by well-known author and developer. . Hibernate/JPA.com Questions? Q ti ? Customized Java EE Training: http://courses.coreservlets. JSP. Struts.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->