Archive for October, 2007

Web site optimization - APPENDIX C n HIBERNATE AND SPRING 309 n

Wednesday, October 17th, 2007

APPENDIX C n HIBERNATE AND SPRING 309 n HIBERNATE AND SPRING 309 Listing C-17 Declaring the OpenSessionInViewInterceptor for Use in the Spring View
The interceptor needs to control the behavior of the session factory, so we must provide it with a reference to the appropriate bean. We can also dictate whether a single Session object will be used for the entire duration of the user request. Setting this to true is the most efficient approach, and therefore the default; however, it has potential side effects, particularly if declarative transactions are not in use. When set to false, individual sessions will be acquired for each DAO operation. The Sample Configuration File Listing C-18 shows the full Spring configuration file of our example application as a handy reference to what s required in creating a Hibernate-based Spring application. Listing C-18. The Complete Spring Configuration File


We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.

Web site translator - 308 APPENDIX C n HIBERNATE AND SPRING APPENDIX

Tuesday, October 16th, 2007

308 APPENDIX C n HIBERNATE AND SPRING APPENDIX C n HIBERNATE AND SPRING Listing C-16. Wrapping the DAO Implementation Bean with Appropriate Transactionality

Managing the Session A familiar problem encountered when using Hibernate is the LazyInitializationException. This occurs when you try to access the lazily loaded attributes of a detached entity typically when the session that loaded it has been closed. This causes problems in Spring when you want to use information obtained from a DAO in a controller in the view to which it forwards the request. By default, a DAO derived from the HibernateDaoSupport class closes the session as soon as any HibernateTemplate methods complete (or as soon as the session is released, if you are not using HibernateTemplate). Entities that have been retrieved from the DAO will therefore become detached from their session. If they are then passed to a view typically a JSP your client code will produce a LazyInitializationException when it tries to access any lazy properties of the entity that were not accessed prior to completion of the original DAO method (or forced to load in some other way). Clearly, marking all the properties of your entities as being eagerly loaded is not practical and typically, it is not possible to determine in advance exactly which properties of your entity should be actively loaded. Instead, Spring provides a mechanism to implement the OpenSessionInView pattern of behavior. This ensures that the Session object is retained until processing of the view is complete. Only then is it closed it must be closed at some point to ensure that your web applications don t leak a Session for every user request! The effect is that with either an OpenSessionInViewInterceptor in your Spring configuration file or an OpenSessionInViewFilter configured in your web.xmlfile, you can access lazily loaded attributes of entities acquired from your DAOs without any risk of the dreaded LazyInitializationException. Note that only one of the two options is required they differ only in their internal details, not the outcome of applying them. Generally, we use the OpenSessionInViewInterceptor, as it is configured like any other Spring bean. Our example application makes use of this to ensure that the lazily loaded articles attribute of the Paper entity can be accessed from the JSP view implementations (see Listing C-17).
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

APPENDIX C n HIBERNATE AND SPRING 307 n (Hosting your own web site)

Monday, October 15th, 2007

APPENDIX C n HIBERNATE AND SPRING 307 n HIBERNATE AND SPRING 307 To support transactional behavior, a transaction manager bean must first be applied to the session factory. Typically, this would be a HibernateTransactionManager in a self-contained application, or a JtaTransactionManager in an environment in which the container is managing transactions. Our application uses the Hibernate transaction manager, as declared in Listing C-14. Listing C-14. Declaring the HibernateTransactionManager Bean
The transaction manager must be notified of the session factory in use so that it can manage the transactions of the database connection configured in the session factory. If you want to be able to use nested transactions so that multiple calls to transactional methods can be made from a method that is itself enclosed in a transaction, you must set the nestedTransactionAllowed property on the HibernateTransactionManager bean. Note that Hibernate does not support the use of savepoints within nested transactions because it is unable to rollback the session cache s state. The transaction boundaries are applied to a bean by wrapping it in a proxy class that then honors the original bean s API as declared in its interface(s). Typically, the basis of the proxy is therefore declared as an abstract bean so that it can be applied to multiple DAO beans as required. For illustrative purposes, our example application also uses this approach (see Listing C-15). Listing C-15. Declaring the Default Transactionality for Our DAO Beans
PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED
With the transaction manager s template prepared, the declaration of any DAO objects must be wrapped in a bean declaration derived from this template. Our wrapped bean is shown in Listing C-16. The lines highlighted in bold are the wrapped bean s declaration since it is only used as a property for the enclosing proxy, it does not need to be assigned an id instead, the id of the paperDao proxy is used when a DAO reference is required. The proxy will honor the PaperDaointerface declared in Listing C-7.
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Web site design and hosting - 306 APPENDIX C n HIBERNATE AND SPRING APPENDIX

Sunday, October 14th, 2007

306 APPENDIX C n HIBERNATE AND SPRING APPENDIX C n HIBERNATE AND SPRING Listing C-11. The createArticle() Method Without HibernateTemplate public Paper createArticle(final Integer paperId,final Article article) { Session session = getSession(); Paper paper = (Paper)session.get(Paper.class,paperId); paper.addArticle(article); session.update(paper); releaseSession(session); return paper; } Regardless of how you use it, configuring your HibernateDaoSupport-derived template is extremely simple. The basic requirement is that you provide its sessionFactory property with a session factory bean from which to obtain Hibernate Session objects (see Listing C-12). Listing C-12. Configuring a HibernateDaoSupport-Derived Bean
In practice, however, this is usually made somewhat more complex by the need to declare the transactional behavior that applies to the DAO s methods. Declarative Transaction Management The getAll() method as implemented in Listings C-8 and C-9 omits any explicit transaction management. It is entirely possible to manage transactions directly you have access to the Hibernate Session object, and this can be used as shown in Listing C-13. Listing C-13. Explicit Transaction Management (Not Recommended) @SuppressWarnings(”unchecked”) public List getAll() { Session session = getSession(); session.beginTransaction(); List papers = (List)session.createQuery(”from Paper”).list(); session.getTransaction().commit(); releaseSession(session); return papers; } However, while this is possible, it is not recommended the use of OpenInViewInterceptor or OpenInViewFilter can prevent this code from behaving as you might expect, as can various other indirectly applied beans. This is equally applicable when you are using HibernateTemplate. Because of these risks, you should favor the use of declarative transaction management. With this, the beans methods are marked as being the boundaries of transactions, and the appropriate transaction isolation level and propagation behavior can be specified.
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

Web hosting domains - APPENDIX C n HIBERNATE AND SPRING 305 n

Saturday, October 13th, 2007

APPENDIX C n HIBERNATE AND SPRING 305 n HIBERNATE AND SPRING 305 Table C-1. The Core HibernateTemplate Methods Method Description bulkUpdate() Performs a bulk update or delete on the database, according to the provided HQL query and entities contains() Determines whether the given object exists as an entity in the database delete() Deletes an entity from the database find() Carries out an HQL query get() Obtains an entity by its id (primary key) persist() Saves an entity to the database refresh() Refreshes an entity from the database save() Saves an entity to the database saveOrUpdate() Saves an entity to the database or updates it as appropriate update() Updates an entity in the database When a more complex set of operations is required than can be achieved in a single line, the execute()method is used to invoke an instance of HibernateCallback. Our example application uses HibernateCallbackto implement its createArticle() method. This is shown in Listing C-10. Listing C-10. Invoking a HibernateCallback Object from the Template s execute() Method public Paper createArticle(final Integer paperId,final Article article) { HibernateCallback callback = new HibernateCallback() { public Object doInHibernate(Session session) { Paper paper = (Paper)session.get(Paper.class,paperId); paper.addArticle(article); session.update(paper); return paper; } }; return (Paper)getHibernateTemplate().execute(callback); } Although this allows us to invoke more complex code from the HibernateTemplate class, and HibernateTemplate obviates the need for specific management of the session, it doesn t make the implementation particularly terse, and probably makes it slightly harder to understand. Listing C-11 shows how the same method can be implemented without using HibernateTemplate.
We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.

304 APPENDIX C (Web site hosting) n HIBERNATE AND SPRING APPENDIX

Friday, October 12th, 2007

304 APPENDIX C n HIBERNATE AND SPRING APPENDIX C n HIBERNATE AND SPRING public interface PaperDao { public List getAll(); public void createPaper(final Paper paper); public Paper getPaper(final Integer paperId); public Paper createArticle(final Integer paperId,final Article article); } Ideally, you should define an interface to specify the methods that your DAO will contain. Our sample application requires a single DAO with a few simple methods (shown in Listing C-7). With the interface clearly specified, your DAO class should then extend the HibernateDaoSupport class and implement the interface that you have defined. Extending HibernateDaoSupport provides a number of get/set pairs for necessary Spring attributes (specifically the sessionFactory attribute) and various helper methods for implementing your DAO. A typical DAO method implementation using these methods is shown in Listing C-8. Listing C-8. Implementing getAll() Using the Methods from the HibernateDaoSupport Class @SuppressWarnings(”unchecked”) public List getAll() { Session session = getSession(); List papers = (List)session.createQuery(”from Paper”).list(); releaseSession(session); return papers; } The getSession() and releaseSession() methods are derived from the DAO class. They are roughly equivalent to the session factory s openSession()method and the session s close() method, respectively. The HibernateDaoSupport class also provides access to an appropriately configured helper object: HibernateTemplate. Using this object, the preceding code can be rewritten as shown in Listing C-9. Listing C-9 Implementing the getAll() Method Using the HibernateTemplate Class @SuppressWarnings(”unchecked”) public List getAll() { return (List)getHibernateTemplate().find(”from Paper”); } This notably reduces the amount of boilerplate session management code that is required to process this simply query. HibernateTemplate provides a set of methods (shown in Table C-1) that allow you to carry out most of the basic Hibernate operations in a similar single line of code.
We recommend high quality webhost to host and run your jsp application: christian web host services.

APPENDIX C n HIBERNATE AND (Web hosting account) SPRING 303 n

Thursday, October 11th, 2007

APPENDIX C n HIBERNATE AND SPRING 303 n HIBERNATE AND SPRING 303 Listing C-6. Configuring Hibernate Purely from Spring
com/hibernatebook/spring/Paper.hbm.xml com/hibernatebook/spring/Article.hbm.xml 0 true org.hibernate.dialect.HSQLDialect
Note that in Listing C-6, purely in order to demonstrate the use of mapping files in a LocalSessionFactoryBean configuration, we omit the specification of a Hibernate AnnotationConfiguration for the configurationClass property, causing it to default to the normal (mapping file based) Hibernate Configuration object. Typically, the mappings themselves are specified in the conventional Hibernate manner through XML mapping files or Java annotations. It would be entirely possible to arrange to configure these externally, but no default Spring classes are provided to achieve this, and it is difficult to see any obvious benefit that would accrue from such an approach. Using Hibernate in Your Spring Beans With your session factory configured as a Spring bean, you can now go on to create DAOs that take advantage of Hibernate s functionality. Here, Spring really starts to come into its own, as it provides you with the invaluable HibernateDaoSupport class to form the basis of your DAOs (see Listing C-7). Listing C-7. Declaring the Interface for Our DAO package com.hibernatebook.spring.dao; import java.util.List; import com.hibernatebook.spring.Article; import com.hibernatebook.spring.Paper;
We recommend high quality webhost to host and run your jsp application: christian web host services.

302 APPENDIX C n HIBERNATE AND SPRING (Web host sites) APPENDIX

Thursday, October 11th, 2007

302 APPENDIX C n HIBERNATE AND SPRING APPENDIX C n HIBERNATE AND SPRING is not the appropriate location for its details to be stored. Moreover, a well-behaved web application will draw its database configuration from a JNDI-provided DataSource object so that connection details can be uniformly managed at deployment time. Spring allows data sources to be managed centrally as beans, and if a JndiObjectFactoryBean bean is used, it can in turn draw its details from JNDI. The LocalSessionFactoryBean therefore provides a dataSource property into which the appropriate Spring DataSource bean can be injected. Typically, to manage a data source from within the Spring configuration, but without deferring the details to a JNDI resource, you would use the DriverManagerDataSource bean (see Listing C-4). Listing C-4. Configuring a Typical BasicDataSource Bean
org.hsqldb.jdbcDriver jdbc:hsqldb:file:/spring/db/springdb;SHUTDOWN=true
Alternatively, if the data source resources are to be drawn from an existing JNDI-accessible data source, then the Spring JndiObjectFactoryBean should be used to represent the data source (see Listing C-5). Listing C-5. Configuring a Typical JndiObjectFactoryBean
It is not just the connection details that can be migrated from the Hibernate configuration file into the Spring configuration. The property attributes and the mappings (class names or mapping file names) can also be assigned during the configuration of a LocalSessionFactory bean (see Listing C-6).
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

APPENDIX C n HIBERNATE AND SPRING (Free web hosting with ftp) 301 n

Wednesday, October 10th, 2007

APPENDIX C n HIBERNATE AND SPRING 301 n HIBERNATE AND SPRING 301
org.hsqldb.jdbcDriver jdbc:hsqldb:file:/spring/db/springdb;SHUTDOWN=true sa 0 true org.hibernate.dialect.HSQLDialect
Spring represents the configured session factory as a LocalSessionFactoryBean. Our example application uses annotations to manage the mappings, so we specify that the Hibernate AnnotationConfiguration type should be used in our bean instead of the default Configuration. nCaution Spring maintains two sets of Hibernate packages: org.springframework.orm.hibernate… for Hibernate 2 functionality, and org.springframework.orm.hibernate3… for Hibernate 3 functionality a single-character difference. Be careful to select the correct one, as debugging the ClassNotFound and similar exceptions that result if you use the wrong one can be extremely time-consuming! We also specify the location and name of the configuration file relative to the classpath as indicated by the classpath: prefix (see Listing C-3). Listing C-3. Configuring a Session Factory Bean in Spring
As noted, our simple web application derives its database connection details from the Hibernate configuration file. However, a larger web application typically needs to provide database resources to other applications, in which case a Hibernate-specific configuration file
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

Bulletproof web design - 300 APPENDIX C n HIBERNATE AND SPRING APPENDIX

Tuesday, October 9th, 2007

300 APPENDIX C n HIBERNATE AND SPRING APPENDIX C n HIBERNATE AND SPRING The Java Standard Template Library JARs The HSQLDB driver JAR The Spring JAR This requires the list of JAR files shown in Listing C-1 to be included in the WEB-INF/lib directory of our example application. Listing C-1. The Required JAR Files antlr-2.7.6rc1.jar asm-attrs.jar asm.jar cglib-2.1.3.jar commons-collections-2.1.1.jar commons-logging-1.0.4.jar dom4j-1.6.1.jar ehcache-1.1.jar ejb3-persistence.jar hibernate-annotations.jar hibernate3.jar hsqldb.jar jdbc2_0-stdext.jar jstl.jar jta.jar spring.jar standard.jar xml-apis.jar Configuring Hibernate from a Spring Application A conventional Hibernate application needs access to its database and the entity mapping information. The point of access to a fully configured Hibernate environment is the session factory, from which Sessionobjects are obtained. Spring provides a bean to represent the session factory, but provides a few additional options in order to configure its resources. In our example application, we take the line of least resistance and use a Hibernate configuration file (hibernate.cfg.xml) to represent both the mapping information and the database configuration. For easy reference when setting up a Spring application, we show a sample Hibernate configuration file in Listing C-2. Listing C-2. Familiar Territory: A Standard Hibernate Configuration File Used in Spring
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.